<code id="ymukc"><xmp id="ymukc">

C#通過ARP獲取Mac與IP的對應表

podc9bw2的頭像 podc9bw2 0 2016-03-02 12:56 0

 基本信息

× 1   

瀏覽數: 24976

分享時間: 2 年 前

1

原理:通過ARP命令查詢,然后返回數據,根據返回數據進行分割保存

最后使用LINQ查詢。

/// <summary>
        /// 獲取ARP查詢字符串
        /// </summary>
        /// <returns></returns>
        private static string GetARPResult()
        {
            Process p = null;
            string output = string.Empty;
            try
            {
                p = Process.Start(new ProcessStartInfo("arp", "-a")
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                });
                output = p.StandardOutput.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw new Exception("IPInfo: Error Retrieving 'arp -a' Results", ex);
            }
            finally
            {
                if (p != null)
                {
                    p.Close();
                }
            }
            return output;
        }

轉換為對應的列表:
/// <summary>
        /// 獲取IP地址與Mac地址對應數據表
        /// </summary>
        /// <returns>Mac-IP</returns>
        public static List<string[]> GetIPInfo()
        {
            try
            {
                var list = new List<string[]>();
                foreach (var arp in FLYFI_SHARE_CONNECTION.GetARPResult().Split(new char[] { '\n', '\r' }))
                {
                    if (!string.IsNullOrEmpty(arp))
                    {
                        var pieces = (from piece in arp.Split(new char[] { ' ', '\t' })
                                      where !string.IsNullOrEmpty(piece)
                                      select piece).ToArray();
                        if (pieces.Length == 3)
                        {
                            //pieces[1]Mac
                            //pieces[0]IP
                            list.Add(new string[2] { pieces[1], pieces[0] });
                        }
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                throw new Exception("IPInfo: Error Parsing 'arp -a' results", ex);
            }
        }

查詢:
/// <summary>
        /// Mac地址轉換為IP地址
        /// </summary>
        /// <param name="str">IP</param>
        /// <returns></returns>
        public static string GetIpFromMac(string str)
        {
            str = str.Trim().ToString().Replace(":", "-");
            var ipinfo = (from ip in FLYFI_SHARE_CONNECTION.GetIPInfo()
                          where ip[0].ToLowerInvariant() == str.ToLowerInvariant()
                          select ip[1]).FirstOrDefault();
            return ipinfo;
        }
還沒有人評論,趕快來搶沙發吧!

  
六合特码资料
<code id="ymukc"><xmp id="ymukc">
<code id="ymukc"><xmp id="ymukc">