笔记:  

    /// <summary>
    /// 获取本地Ip地址
    /// </summary>
    /// <returns></returns>
    public string GetLocalIp()
    {
        var addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
        var ip = addressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString();
        return ip;
    }

  注意一下,上面的addressList参数包含了包含了IPv4和IPv6的地址信息,如果按照了虚拟机(如vmware等),启用了多个网络适配器,那么IPv4和IPv6可能会存在多个地址,具体需要哪个可自行判断。

  比如更准确的做法:  

    /// <summary>
    /// 获取本地Ip地址
    /// </summary>
    /// <returns></returns>
    public static string GetLocalIp()
    {
        var addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
        var ips = addressList.Where(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                .Select(address => address.ToString()).ToArray();
        if (ips.Length == 1)
        {
            return ips.First();
        }
        return ips.Where(address => !address.EndsWith(".1")).FirstOrDefault() ?? ips.FirstOrDefault();
    }

 

版权声明:本文为shanfeng1000原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/shanfeng1000/p/13877082.html