Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address and adapter description using C#

I got a problem synchronizing the "IP address and Description".

The objective is this:

Get the IP address and what is the description?

Example:

| Atheros Azx1234 Wireless Adapter |

|192.168.1.55                      |

But the outcome is not what I expected...

This is my code feel free to try...

private void button1_Click(object sender, EventArgs e)
{
    NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
    IPHostEntry host;
    host = Dns.GetHostEntry(Dns.GetHostName());

    foreach (NetworkInterface adapter in interfaces)
    {
        foreach (IPAddress ip in host.AddressList)
        {
            if ((adapter.OperationalStatus.ToString() == "Up") && // I have a problem with this condition
                (ip.AddressFamily == AddressFamily.InterNetwork))
            {
                MessageBox.Show(ip.ToString(), adapter.Description.ToString());
            }
        }
    }
}

How can I fix this problem?

like image 896
Roise Escalera Avatar asked Nov 01 '12 10:11

Roise Escalera


1 Answers

The problem in your code is that you do not use the associated IP addresses for the given adapter. Instead of matching all IP addresses to every adapter use only the IP addresses associated with the current adapter:

NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces)
{
    var ipProps = adapter.GetIPProperties();

    foreach (var ip in ipProps.UnicastAddresses)
    {
        if ((adapter.OperationalStatus == OperationalStatus.Up)
        && (ip.Address.AddressFamily == AddressFamily.InterNetwork))
        {
            Console.Out.WriteLine(ip.Address.ToString() + "|" + adapter.Description.ToString());
        }
    }
}
like image 134
Hans Avatar answered Sep 21 '22 23:09

Hans