Skip to content
欢迎扫码关注公众号

.NET Core 获取本地 IP 地址

网上搜到的都是 Web 服务器通过当前上下文 HttpContext 来获取本机的 IP 地址,

csharp
HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString()

那么控制台程序中如何获取本机 IP 呢?

我这里使用了 System.Net.Dns 类的 GetHostEntryGetHostName 方法,获取的 IP 地址列表中取第一个地址族(address family)为 AddressFamily.InterNetwork 的 IP。如果是获取 IPv6 的地址,地址族应为 AddressFamily.InterNetworkV6

注意

由于 GetHostEntry 方法获取到是 IP 地址的数组,所以我也不确定取第一个是否是对的(虽然本机调试的时候是对的上的)。

csharp
System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString()

参考文档

  1. Dns.GetHostEntry Method
  2. IPAddress Class
  3. IPAddress.IsLoopback(IPAddress) Method

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.