ArpTool.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. namespace DllEapFileUpload
  7. {
  8. public class ArpTool
  9. {
  10. /// <summary>
  11. /// 获取ARP查询字符串
  12. /// </summary>
  13. /// <returns></returns>
  14. private static string GetARPResult()
  15. {
  16. Process p = null;
  17. string output = string.Empty;
  18. try
  19. {
  20. p = Process.Start(new ProcessStartInfo("arp", "-a")
  21. {
  22. CreateNoWindow = true,
  23. UseShellExecute = false,
  24. RedirectStandardOutput = true
  25. });
  26. output = p.StandardOutput.ReadToEnd();
  27. }
  28. catch (Exception ex)
  29. {
  30. //throw new Exception("IPInfo: Error Retrieving 'arp -a' Results", ex);
  31. LogBLL.Err("IPInfo: Error Retrieving 'arp -a' Results", ex);
  32. }
  33. finally
  34. {
  35. if (p != null)
  36. {
  37. p.Close();
  38. }
  39. }
  40. return output;
  41. }
  42. /// <summary>
  43. /// 获取IP地址与Mac地址对应数据表
  44. /// </summary>
  45. /// <returns>Mac-IP</returns>
  46. public static List<string[]> GetIPInfo()
  47. {
  48. try
  49. {
  50. var list = new List<string[]>();
  51. foreach (var arp in GetARPResult().Split(new char[] { '\n', '\r' }))
  52. {
  53. if (!string.IsNullOrEmpty(arp))
  54. {
  55. var pieces = (from piece in arp.Split(new char[] { ' ', '\t' })
  56. where !string.IsNullOrEmpty(piece)
  57. select piece).ToArray();
  58. if (pieces.Length == 3)
  59. {
  60. //pieces[1]Mac
  61. //pieces[0]IP
  62. list.Add(new string[2] { pieces[1], pieces[0] });
  63. }
  64. }
  65. }
  66. return list;
  67. }
  68. catch (Exception ex)
  69. {
  70. LogBLL.Err("IPInfo: Error Retrieving 'arp -a' Results", ex);
  71. return null;
  72. //throw new Exception("IPInfo: Error Parsing 'arp -a' results", ex);
  73. }
  74. }
  75. /// <summary>
  76. /// Mac地址转换为IP地址
  77. /// </summary>
  78. /// <param name="str">IP</param>
  79. /// <returns></returns>
  80. public static string GetIpFromMac(string str)
  81. {
  82. //str = str.Trim().ToString().Replace(":", "-");
  83. List<string[]> getipinfo = GetIPInfo();
  84. string ipinfo = (from ip in getipinfo
  85. where ip[1].ToLowerInvariant() == str.ToLowerInvariant()
  86. select ip[0]).FirstOrDefault();
  87. if (string.IsNullOrEmpty(ipinfo))
  88. {
  89. return "";
  90. }
  91. else
  92. {
  93. return ipinfo.ToUpperInvariant();
  94. }
  95. }
  96. }
  97. }