0

I want to get the IP Information from my PC. I can get the Description of the NIC, the IP address and the Subnet Mask, here is my code:

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
            {
                foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                {

                    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        Nics.Add(ni.Description);
                        IPs.Add(ip.Address.ToString());
                        SubnetMasks.Add(ip.IPv4Mask.ToString());


                    }
                }
            }
        }

so first of all, this shows me some strange NIC's that i don't even see when I type in "ipconfig /all" and things like that the bluetooth gets an IP Adress. Is there a way that I just get the one that has a connection? And get the Default Gateway?

EDIT:

"Nics", "IPs" and "SubnetMasks" are ArrayLists.

EDIT2:

I used this code:

string asdf = "";
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                MessageBox.Show(ip.ToString());
                asdf = ip.ToString();
            }
        }
        textBox1.Text = asdf;

But the Problem is, that I have VMWare and some other NICS that have IP Adresses and the MessageBox shows me all the ip adresses - is it ALWAYS, that the used one is the last? I mean, what if I use this code on another PC and there the used IP Address is not the last in host.AddressList, then it will display the wrong IP Adress.

jochot
  • 167
  • 1
  • 13
  • Like this http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c? – sondergard May 28 '14 at 15:28
  • this may have some relevant information: http://stackoverflow.com/questions/13634868/get-the-default-gateway (top answer AND comment) – bdimag May 28 '14 at 15:28
  • Check for `OperationalStatus.Up` ? Also, `ArrayList` got replaced 10 years ago, it looks like you should be using `List`. – Ben Voigt May 28 '14 at 15:42
  • so I changed my code, but I'm not sure if it displays always the right IP Address - because it runs through all the IP Addresses and only saves the last - is the used one ALWAYS the last one? If not I would get the false IP Address... – jochot May 30 '14 at 11:40
  • What is "the right IP address" when a system has multiple configured? – CodeCaster May 30 '14 at 11:42
  • The one my PC is using in the LAN, not the VMWare IP Addresses. – jochot May 30 '14 at 11:51

0 Answers0