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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With