vakas vakas - 3 months ago 16
ASP.NET (C#) Question

how to determine whether an IP address in 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.

Answer

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;
}
Comments