.net core获取本地Ip地址的方法

时间:2024-07-22 00:06:20

  笔记:  

    /// <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();
}