-3

So I am having issues gettign someting as simple as the Wireless adapter IP address in C#. I don't feel that it should be this difficult. The PC I am ussing is only WiFi currently so running the below code only returns localhost as an IP address. Looks Like I am only looking at the ethernet interface and not wireless.

Please help.

    public static string GetIPAddress()
    {
        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
            }
        }
        return localIP;
    }
  • 1
    Does this answer your question? [How do I get the network interface and its right IPv4 address?](https://stackoverflow.com/questions/9855230/how-do-i-get-the-network-interface-and-its-right-ipv4-address) – quaabaam Sep 09 '20 at 23:50
  • Fix your bug: `return localIP;` from inside the `foreach` otherwise you iterate past all the addresses you might be interested in and always return the last. – AlanK Sep 09 '20 at 23:51

1 Answers1

0

This should do the trick. You can either remove or let the NetworkInterfacetype == Network.

foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       Console.WriteLine(ni.Name);
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               Console.WriteLine(ip.Address.ToString());
           }
       }
   }  
}

credits go to @bwall --> How do I get the network interface and its right IPv4 address?

abo
  • 131
  • 4
  • 1
    If you are going to use someone else's answer, at least add something to it in your own words, or an explanation or make it better in some way. Its not a good look otherwise. – TheGeneral Sep 09 '20 at 23:55
  • I don't understand that too much. I don't know how to remove the console part. I just want the IP to a string that I can put into a label. – Russell Gray Sep 10 '20 at 00:08