Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 882
Eugene Avatar asked May 17 '18 08:05

Eugene


People also ask

Where can I find the IPv4 address?

First, click on your Start Menu and type cmd in the search box and press enter. A black and white window will open where you will type ipconfig /all and press enter. There is a space between the command ipconfig and the switch of /all. Your ip address will be the IPv4 address.

How do I find my local network IP address?

Open the Start menu and type cmd to open the Command Prompt. Type ipconfig into the Command Prompt and press Enter. The tool will return a set of data that includes your IP address.

How do I find my Ethernet IP address C#?

Get Local IP Address With NetworkInterface Class in C#The GetAllNetworkInterfaces() function in the NetworkInterface class gives us all the network interfaces on our local machine. The NetworkInterfaceType property in the NetworkInterface class is used to get the type of the network interface.


1 Answers

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();
}
like image 86
Evk Avatar answered Oct 23 '22 10:10

Evk