问题
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