Get local IP address

前端 未结 26 2861
野的像风
野的像风 2020-11-22 10:07

In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:

String strHostName = string.Empty;         


        
26条回答
  •  失恋的感觉
    2020-11-22 10:51

    Just an updated version of mine using LINQ:

    /// 
    /// Gets the local Ipv4.
    /// 
    /// The local Ipv4.
    /// Network interface type.
    IPAddress GetLocalIPv4(NetworkInterfaceType networkInterfaceType)
    {
        var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.NetworkInterfaceType == networkInterfaceType && i.OperationalStatus == OperationalStatus.Up);
    
        foreach (var networkInterface in networkInterfaces)
        {
            var adapterProperties = networkInterface.GetIPProperties();
    
            if (adapterProperties.GatewayAddresses.FirstOrDefault() == null)
                    continue;
            foreach (var ip in networkInterface.GetIPProperties().UnicastAddresses)
            {
                if (ip.Address.AddressFamily != AddressFamily.InterNetwork)
                        continue;
    
                return ip.Address;
            }
        }
    
        return null;
    }
    

提交回复
热议问题