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

Eug*_*ene 5 c# ip-address asp.net-core-mvc asp.net-core-2.0

在哪个运行WebService.就像我可以进入的那样cmd.exe > ipconfig: 在此输入图像描述

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

.UseKestrel(opts => 
    { 
        opts.Listen(/*LocalIPv4ActiveAddress*/, 5000);
    }) 
Run Code Online (Sandbox Code Playgroud)

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

Evk*_*Evk 7

你可以尝试这样的事情:

// 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();
}
Run Code Online (Sandbox Code Playgroud)

  • @Eugene这是使系统过于通用的症状。:-) (3认同)
  • docker环境中的一些问题,“ System.PlatformNotSupportedException:请求的信息在当前平台上不可用。\ n在System.Net.NetworkInformation.LinuxNetworkInterface.get_Speed()” (3认同)
  • 我想知道为什么解决方案需要在 net core 中这么多指令才能获得如此简单的信息 (2认同)