Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether an IP address is private?

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.

like image 345
vakas Avatar asked Nov 13 '11 18:11

vakas


People also ask

How do you tell if an IP is private or public?

You can check an IP address against the ranges for public vs private IP addresses to see if a particular IP address is public or private. All private IP addresses begin with 10, 172, or 192, though some public IP addresses may also begin with 172 and 192.

Is 192.168 private or public?

192.168 is usually a private IP address. The range of numbers between 192.168. 0.0 and 192.168. 255.255 is reserved for private IP addresses.

Can you look up a private IP address?

Windows. Search for cmd in the Windows search bar, then in the command line prompt, type ipconfig to view the private IP address. Mac. Select system preferences, then click on network to view the private IP address.


1 Answers

A more detailed response is here:

private bool _IsPrivate(string ipAddress) {     int[] ipParts = ipAddress.Split(new String[] { "." }, StringSplitOptions.RemoveEmptyEntries)                              .Select(s => int.Parse(s)).ToArray();     // in private ip range     if (ipParts[0] == 10 ||         (ipParts[0] == 192 && ipParts[1] == 168) ||         (ipParts[0] == 172 && (ipParts[1] >= 16 && ipParts[1] <= 31))) {         return true;     }      // IP Address is probably public.     // This doesn't catch some VPN ranges like OpenVPN and Hamachi.     return false; } 
like image 98
Gabriel Graves Avatar answered Sep 30 '22 22:09

Gabriel Graves