8

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

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.

3
  • I use "HttpContext.Connection.LocalIpAddress.ToString()" for a MVC Application, it may be the same... Commented May 17, 2018 at 8:29
  • Seems that doesnt work, .NET Core doesn't provide Connection.LocalIpAddress.ToString() part.
    – Eugene
    Commented May 17, 2018 at 8:34
  • You could probably just use 0.0.0.0 to listen to all interfaces, if this is supported by Kestrel.
    – Gene
    Commented May 17, 2018 at 8:34

2 Answers 2

14

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();
}
5
  • 2
    I wonder why the solution requires so many instructions in net core to get such simple information 🤔
    – Eugene
    Commented May 17, 2018 at 9:11
  • 3
    @Eugene It's a symptom of making a system overly generic. :-)
    – RonC
    Commented May 17, 2018 at 13:02
  • 4
    Some problems on docker enviorment, System.PlatformNotSupportedException: The information requested in unavailable on the current platform.\n at System.Net.NetworkInformation.LinuxNetworkInterface.get_Speed()
    – live2
    Commented Jan 23, 2019 at 13:44
  • 1
    Not worked in linux. have tried same code with asp.net core 3.1 application Commented Mar 4, 2020 at 11:50
  • Proof of non linux here. dotnetfiddle.net/nnQ66w Upvote for this for windows answer. Commented May 8, 2020 at 13:55
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.