So far I have this code:
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
{
// Ignore loop-back addresses & IPv6
if (!IPAddress.IsLoopback(uniCast.Address) &&
uniCast.Address.AddressFamily!= AddressFamily.InterNetworkV6)
Addresses.Add(uniCast.Address);
}
}
How can I filter the private IP addresses as well? In the same way I am filtering the loopback IP addresses.
Added IPv6 and localhost cases.
The private address ranges are defined in RFC1918. They are:
You might also want to filter out link-local addresses (169.254/16) as defined in RFC3927.
The best way to do this would be an extension method to the IP Address class
Then, one may call the method on an instance of the IP address class
Use the ranges defined in the RFC (as suggested by Anders); than use regular expression to detect/remove the private IP address from the list.
Here is a sample RegEx to detect private IP addresses. (Not tested by me)
A more detailed response is here: