c# - .NET Core 2.x如何获取当前事件的本地网络IPv4地址?

标签 c# asp.net-core-mvc ip-address asp.net-core-2.0

在其上运行 WebService。就像我可以在 cmd.exe > ipconfig 中得到的一样: enter image description here

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

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

因此我可以使用不同的事件网络接口(interface)(WiFi || 以太网)和不同的本地网络 IP 地址切换我的开发机器。

最佳答案

你可以尝试这样的事情:

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

关于c# - .NET Core 2.x如何获取当前事件的本地网络IPv4地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50386546/

相关文章:

javascript - 浏览器不在启用 CORS 的情况下跨域发送 cookie

asp.net - 在 ASP.NET Core 中使用防伪 cookie,但使用非默认 CookieName

c# - ASP.NET 核心 (MVC) : Can't get to the Login HttpPost action in controller

asp.net-core - 从 ASP.NET Core 中的 View 访问配置

c# - 如何让两个应用程序通过 LAN 找到并连接?

c# - Windows 应用商店验证订阅服务器端

c# - 保存图像缩略图而不是 MediaStore.ActionImageCapture 中的完整图像

arrays - 如何在 Ruby 中手动将整数转换为 IP 地址

java - 从 WebSphere 中的请求获取客户端 IP 地址

python - python 如何以不同的时间间隔递增?