.net core获取本机IP地址

传统使用中,一般使用下面方法

 //获取本机可用的IP地址
var ips = Dns.GetHostAddresses(Dns.GetHostName()).Where(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.ToString()).ToList();

但是发现,在Linux环境中,无法获取到IP地址,应该采用如下方法:

​
string localIp = NetworkInterface.GetAllNetworkInterfaces()
                .Select(p => p.GetIPProperties())
                .SelectMany(p => p.UnicastAddresses)
                .FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address.ToString();

​

 

你可能感兴趣的:(C#常用工具类与开发技巧,获取本机IP,.net,core)