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

这一生的挚爱 提交于 2020-01-03 10:56:27

问题


On which is running the WebService. Like the one I can get in cmd.exe > ipconfig:

What I would like to achieve is automatic IP configuration of Kestrel, like:

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

So I can switch my development machines with different active network interfaces (WiFi || Ethernet) and different local network IP addresses.


回答1:


You can try something like this:

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



回答2:


see the docs

First you will find addresses like this in the return, discard the ones of family InterNetworkV6 or v4 according to your need and retain only the IPv4 or IPv6 ones?

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


来源:https://stackoverflow.com/questions/50386546/net-core-2-x-how-to-get-the-current-active-local-network-ipv4-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!