In SharpPCap How do I find the IP Address of the D

2019-05-14 00:44发布

问题:

I am using a WinPCapDevice and have already initialized it. I just want to be able to get the IP from that device and I cannot find anywhere how to extract the IP address of the Device. If there isnt a way to do it then is there another way to get the IP address of a WinPCapDevice so that I can check it against a list of IPAddresses?

Here is the small chunk of code that I am talking about.

        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {

                localIPAddress = ip.ToString();
                //Want to check if my WinPCapDevice device's IP is equal to ip
            }
        }

回答1:

The WinPcapDevice class contains a property called Addresses. This property holds all addresses (IP) associated with the device:

string localIPAddress = "...";

WinPcapDeviceList devices = WinPcapDeviceList.Instance;

foreach(WinPcapDevice dev in devices)
{
  Console.Out.WriteLine("{0}", dev.Description);

  foreach(PcapAddress addr in dev.Addresses)
  {
    if(addr.Addr != null && addr.Addr.ipAddress != null)
    {
      Console.Out.WriteLine(addr.Addr.ipAddress);

      if(localIPAddress == addr.Addr.ipAddress.ToString())
      {
        Console.Out.WriteLine("Capture device found");           
      }
    }
  }
}

Of course, you could also use the CaptureDeviceList class to get a list of specific devices. Every device in this list implements ICaptureDevice. You then have to cast to a WinPcapDevice, a LibPcapLiveDevice or a AirPcapDevice in order to access the Address property.

Hope, this helps.



标签: c# sharppcap