1

I want to get the local IP-Address from any Windows device. It works fine for my Desktop-PC. But when I try to get the IP of my laptop or my surface I always get 123.123.123.123.

foreach (NetworkInterface nInterface in NetworkInterface.GetAllNetworkInterfaces()) {
    if (nInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nInterface.OperationalStatus == OperationalStatus.Up)
        foreach (var ip in nInterface.GetIPProperties().UnicastAddresses)
            if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                return ip.Address;
}

return IPAddress.Parse("123.123.123.123"); // Only for visualization, that none of the addresses fulfilled the conditions

Do I need to add another NetworkInterfaceType?

Kaskorian
  • 426
  • 3
  • 18

1 Answers1

2

Your function is effectively asking for Wired Ethernet IPs only. Most of the time, a laptop won't have a Wired Ethernet address, but rather have a Wifi adapter with an address. So, you can either look for the Wireless IP:

foreach (NetworkInterface nInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    if (nInterface.OperationalStatus == OperationalStatus.Up)
    {
        // Using a switch statement to make it a litte easier to change the logic
        switch (nInterface.NetworkInterfaceType)
        {
            case NetworkInterfaceType.Ethernet:
            case NetworkInterfaceType.Wireless80211:
                foreach (var ip in nInterface.GetIPProperties().UnicastAddresses)
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        return ip.Address;
                break;
        }
    }
}

Alternatively, you could instead explicitly ignore some network types:

        // Using a switch statement to make it a litte easier to change the logic
        switch (nInterface.NetworkInterfaceType)
        {
            case NetworkInterfaceType.Loopback:
                // ignore this type
                break;
            // Anything else that's running is considered valid
            default:
                foreach (var ip in nInterface.GetIPProperties().UnicastAddresses)
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        return ip.Address;
                break;
        }
Anon Coward
  • 9,784
  • 3
  • 26
  • 37