.NET Core 2.x 如何获取当前活动的本地网络IPv4地址?

.NET Core 2.x how to get the current active local network IPv4 address?

WebService 位于 运行 之上。就像我可以在 cmd.exe > ipconfig 中得到的一样:

我想实现的是Kestrel的自动IP配置,比如:

.UseKestrel(opts => 
    { 
        opts.Listen(/*LocalIPv4ActiveAddress*/, 5000);
    }) 

所以我可以用不同的活动网络接口(WiFi || 以太网)和不同的本地网络 IP 地址切换我的开发机器。

see the docs

return 中的第一个 you will find addresses like this, 丢弃 family InterNetworkV6 or v4 according to your need 的那些,只保留 IPv4 或 IPv6 的?

something like this

// Display the ScopeId property in case of IPV6 addresses.
if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
  Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());

您可以尝试这样的操作:

// order interfaces by speed and filter out down and loopback
// take first of the remaining
var firstUpInterface = NetworkInterface.GetAllNetworkInterfaces()
    .OrderByDescending(c => c.Speed)
    .FirstOrDefault(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up);
if (firstUpInterface != null) {
    var props = firstUpInterface.GetIPProperties();
    // get first IPV4 address assigned to this interface
    var firstIpV4Address = props.UnicastAddresses
        .Where(c => c.Address.AddressFamily == AddressFamily.InterNetwork)
        .Select(c => c.Address)
        .FirstOrDefault();
}