Get IP address and adapter description using C#

13,221

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());
        }
    }
}
Share:
13,221
Roise Escalera
Author by

Roise Escalera

Updated on June 15, 2022

Comments

  • Roise Escalera
    Roise Escalera almost 2 years

    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?