查找接口和 IP 地址(C# 中的 arp)

本文关键字:中的 arp 地址 接口 IP 查找 | 更新日期: 2023-09-27 18:32:26

我有一个简单的问题,但由于缺乏 C# 经验,我无法实现它。

当我打开cmd并键入arp -a命令时,它向我显示所有接口和IP地址都在路由。

所以,我的目标是在 C# 中实现上述过程并获得 IP、Mac 等......有人可以帮助我解决这个技巧吗?我将不胜感激。谢谢

查找接口和 IP 地址(C# 中的 arp)

Chris Pietschmann写了一篇关于你正在寻找什么的博客文章。

它模仿"arp -a"命令。

IPInfo类:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
/// <summary>
/// This class allows you to retrieve the IP Address and Host Name for a specific machine on the local network when you only know it's MAC Address.
/// </summary>
public class IPInfo
{
    public IPInfo(string macAddress, string ipAddress)
    {
        this.MacAddress = macAddress;
        this.IPAddress = ipAddress;
    }
    public string MacAddress { get; private set; }
    public string IPAddress { get; private set; }
    private string _HostName = string.Empty;
    public string HostName
    {
        get
        {
            if (string.IsNullOrEmpty(this._HostName))
            {
                try
                {
                    // Retrieve the "Host Name" for this IP Address. This is the "Name" of the machine.
                    this._HostName = Dns.GetHostEntry(this.IPAddress).HostName;
                }
                catch
                {
                    this._HostName = string.Empty;
                }
            }
            return this._HostName;
        }
    }

    #region "Static Methods"
    /// <summary>
    /// Retrieves the IPInfo for the machine on the local network with the specified MAC Address.
    /// </summary>
    /// <param name="macAddress">The MAC Address of the IPInfo to retrieve.</param>
    /// <returns></returns>
    public static IPInfo GetIPInfo(string macAddress)
    {
        var ipinfo = (from ip in IPInfo.GetIPInfo()
                  where ip.MacAddress.ToLowerInvariant() == macAddress.ToLowerInvariant()
                  select ip).FirstOrDefault();
        return ipinfo;
    }
    /// <summary>
    /// Retrieves the IPInfo for All machines on the local network.
    /// </summary>
    /// <returns></returns>
    public static List<IPInfo> GetIPInfo()
    {
        try
        {
            var list = new List<IPInfo>();
            foreach (var arp in GetARPResult().Split(new char[] { ''n', ''r' }))
            {
                // Parse out all the MAC / IP Address combinations
                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)
                    {
                        list.Add(new IPInfo(pieces[1], pieces[0]));
                    }
                }
            }
            // Return list of IPInfo objects containing MAC / IP Address combinations
            return list;
        }
        catch(Exception ex)
        {
            throw new Exception("IPInfo: Error Parsing 'arp -a' results", ex);
        }
    }
    /// <summary>
    /// This runs the "arp" utility in Windows to retrieve all the MAC / IP Address entries.
    /// </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();
            p.Close();
        }
        catch(Exception ex)
        {
            throw new Exception("IPInfo: Error Retrieving 'arp -a' Results", ex);
        }
        finally
        {
            if (p != null)
            {
                p.Close();
            }
        }
        return output;
    }
    #endregion
}

太好了!!我正在使用它来检测网络上的新设备(并查看是否允许使用mac)。我添加了一些东西(见下文)。非常感谢克里斯·皮奇曼!!

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
namespace DescubrimientoDeRed
{
    //This Class Holds the information for each IP/MAC
    public class IPInfo
    {
        private string _macAddress;
        private string _ipAddress;
        public string IpAddress
        {
            get { return _ipAddress; }
            set { _ipAddress = value; }
        }
        public string MacAddress
        {
            get { return _macAddress; }
            set { _macAddress = value; }
        }
        public IPInfo(string pmacAddress, string pipAddress)
        {
            this.MacAddress = pmacAddress;
            this.IpAddress = pipAddress;
        }
    }
    //This Class holds the IP of each one of the computer interfaces and a list of the
    //IPs/MAC found over that interface
    public class AdaptadorDeRed
    {
        private string _Interfaz;
        private List<IPInfo> _IPsInterfaz;
        public List<IPInfo> IPsInterfaz
        {
            get { return _IPsInterfaz; }
            set { _IPsInterfaz = value; }
        }
        public string Interfaz
        {
            get { return _Interfaz; }
            set { _Interfaz = value; }
        }
        public AdaptadorDeRed(string pInterfaz)
        {
            Interfaz = pInterfaz;
            _IPsInterfaz = new List<IPInfo>();
        }
    }
    //The following class has the important methods
    public class NetInfo
    {
        //ARPtheNet
        //This is the procedure that runs the arp command and returns a text output
        private static string ARPtheNet()
        {
            //this is the process that will run the arp
            Process p = null;
            //this string will capture the output
            string output = string.Empty;
            try
            {
                //to the Process we will give the name of the file (which is the command we use on the cmd and a string with the particular parameters
                p = Process.Start(new ProcessStartInfo("arp", "-a")
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                });
                //we store the output into the string
                output = p.StandardOutput.ReadToEnd();
                //then we close te process
                p.Close();
            }
            catch (Exception ex)
            {
                //If something goes wrong we throw a message with the name of the failing component, and the exception itself
                throw new Exception("NetInfo: Error al realizar un ARP a la red", ex);
            }
            finally
            {
                //whether everything goes right or wrong, we need to close the process..
                if (p != null)
                {
                    p.Close();
                }
            }
            return output;
        }
        //This is the procedure that will read the text from the procedure ARPtheNet and create the objects to have a nice result
        public List<AdaptadorDeRed> GetARPTheNet()
        {
            try
            {
                //This is the list that holds the interfaces (where each one of those, holds the ips)
                List<AdaptadorDeRed> list = new List<AdaptadorDeRed>();
                //Need to declare this outside the "ifs" otherwise these objects will not be accessible from all the places I need.
                AdaptadorDeRed adr = null;
                IPInfo ipi = null;

                //Line by Line we move throw the text of the ARPtheNet result
                foreach (var arp in ARPtheNet().Split(new char[] { ''n', ''r' }))
                {
                    //if the strings has texto on it...
                    if (!string.IsNullOrEmpty(arp))
                    {
                        //If the text has a ":", means that this line has the IP of the particular Interface like:
                        //Interface: 192.168.0.1 --- 0x17 that means either is the first interface we have found, 
                        //or we already have an interface with ips and we have found a new one. 
                        if (arp.IndexOf(":") > 1)
                        {
                            //So if the interfaces is not null and have IPs, we add it to the list and set it null in order to create a new one for the one we just found.
                            if (adr != null && adr.IPsInterfaz.Count > 0)
                            {
                                list.Add(adr);
                                adr = null;
                            }
                            //either way, we create a new adapter
                            adr = new AdaptadorDeRed(arp.Substring(10, arp.IndexOf("---") - 11));
                        }
                        else 
                        {
                            //Need to split the line in as many spaces or tabs we found.
                            var pieces = (from piece in arp.Split(new char[] { ' ', ''t' })
                                          where !string.IsNullOrEmpty(piece)
                                          select piece).ToArray();
                            //the onew that has 3 pieces is because the are like "192.168.0.1", "ff-ff-ff-ff-ff", "dynamic".
                            if (pieces.Length == 3)
                            { 
                                //we add it to the list of the particular interface
                                adr.IPsInterfaz.Add(new IPInfo(pieces[1], pieces[0]));
                            }
                        }
                    }
                }
                //When we get to the end of the text, we are not going to find another ":", so if the adapter is not null and has ips on it we need to add it to the list. 
                if (adr != null && adr.IPsInterfaz.Count > 0) list.Add(adr);
                //then we return the list.
                return list;
            }
            catch (Exception ex)
            {
                throw new Exception("GetARPTheNet: Error al recuperar datos", ex);
            }
        }
    }
}