2012-04-28 1 views
2

나는 간단한 질문이 있지만, C#에서 경험이 부족하다는 것을 구현할 수 없다.인터페이스와 IP 주소를 찾는다. (C#의 arp)

cmd를 열고 arp -a 명령을 입력하면 모든 인터페이스가 표시되고 IP 주소가 라우팅됩니다.

내 목표는 C#에서 위의 프로세스를 구현하고 ip, mac 등을 얻는 것입니다. 누군가이 트릭을 도와 줄 수 있습니까? 나는 크게 감사 할 것입니다. 감사합니다

답변

4

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 
} 



>> Direct Download Here <<


+0

다른 서브넷에서 작동합니까? – Gobliins

+4

Mimics? 이 것은 arp -a를 실행하고 출력을 구문 분석합니다. –

+0

GetIPInfo() 로컬 네트워크의 컴퓨터가 아닌 arp 항목을 검색합니다. – Aferrercrafter

1

Excelent! 나는 네트워크에서 새로운 장치를 탐지하기 위해이 장치를 사용하고있다. 몇 가지를 추가했습니다 (아래 참조). 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 retruns 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 (wich 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 everithing goes right or wrong, we nedd 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 accesible 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", "Dinamyc". 
          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); 
      } 

     } 

    } 
}