Get local IP address

前端 未结 26 2614
野的像风
野的像风 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:47

    This returns addresses from any interfaces that have gateway addresses and unicast addresses in two separate lists, IPV4 and IPV6.

    public static (List V4, List V6) GetLocal()
    {
        List foundV4 = new List();
        List foundV6 = new List();
    
        NetworkInterface.GetAllNetworkInterfaces().ToList().ForEach(ni =>
        {
            if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
            {
                ni.GetIPProperties().UnicastAddresses.ToList().ForEach(ua =>
                {
                    if (ua.Address.AddressFamily == AddressFamily.InterNetwork) foundV4.Add(ua.Address);
                    if (ua.Address.AddressFamily == AddressFamily.InterNetworkV6) foundV6.Add(ua.Address);
                });
            }
        });
    
        return (foundV4.Distinct().ToList(), foundV6.Distinct().ToList());
    }
    

提交回复
热议问题