6

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roise Escalera
  • 63
  • 1
  • 1
  • 4

1 Answers1

12

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());
        }
    }
}
Rand Random
  • 7,300
  • 10
  • 40
  • 88
Hans
  • 12,902
  • 2
  • 57
  • 60
  • This must be the solution, that's it +1 – Nikola Davidovic Nov 01 '12 at 11:00
  • **@Hans : I have a 2 questions for you 1st how can we prevent a Loopback address from previewing in message box? 2nd How can i accept your answer? lol ** – Roise Escalera Nov 01 '12 at 11:20
  • @RoiseEscalera: You can filter the loopback address by adding the following condition to your if statement: ip.Address.Equals(IPAddress.Loopback) == false. To accept my answer please click on the hollow check (tick mark) sign below the voting arrows. – Hans Nov 01 '12 at 11:25