find interfaces and ip addresses (arp in C#)

徘徊边缘 提交于 2019-12-22 18:45:47

问题


i have a simple question but im not able to implement it cuz of lack of experience on C#.

when i open cmd and type arp -a command, it shows me all interfaces and ip addresses are routing.

so, my aim is to implement above process in C# and get ip, mac etc... could somebody help me out on this trick? i would greatly appreciate. thanks


回答1:


Chris Pietschmann wrote a blog post on what you're looking for.

It mimics the "arp -a" command.

IPInfo Class:

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
}



回答2:


Excellent!! I am using it to detect new devices on the network (and see if the are allowed macs or not). I've added a few things (see below). Thanks a lot Chris Pietschmann!!!

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);
            }
        }
    }
}


来源:https://stackoverflow.com/questions/10360933/find-interfaces-and-ip-addresses-arp-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!