C# – Finding my machine’s local IP Address and not the VM’s

I’m refining Andrej Arh’s answer, as the IP Address reported by GatewayAddresses can also be “0.0.0.0” instead of just null:

    public static string GetPhysicalIPAdress()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
            if (addr != null && !addr.Address.ToString().Equals("0.0.0.0"))
            {
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            return ip.Address.ToString();
                        }
                    }
                }
            }
        }
        return String.Empty;
    }

Leave a Comment