Reputation: 8791
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?
Upvotes: 3
Views: 220
Reputation: 3598
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.
Upvotes: 2