Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get currently working ip address

Tags:

c#

I am seeking for a solution which allows me to get the currently working/(in use) ip address of my pc/laptop.

What I mean is I might be in LAN and then switch to WLAN. The ip addy will change and I need to stay up to date.

That is why I am not happy with approaches I found on the internet like IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

What is the best approach for this?

like image 354
dev hedgehog Avatar asked Dec 13 '25 18:12

dev hedgehog


1 Answers

You can look up the active interfaces of the machine like this:

var interfaces = NetworkInterface.GetAllNetworkInterfaces().Where(a => a.OperationalStatus == OperationalStatus.Up);

var addresses = interfaces.First().GetIPProperties().UnicastAddresses.Where(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

The Address property of any item in addresses holds the ip. From there you could monitor the adapters and decide when you need to switch over and what address to bind to.

like image 101
rdoubleui Avatar answered Dec 16 '25 09:12

rdoubleui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!