Check if ip is private

In many situations we need to check if ip is private, for security purposes when logging in to system you need to
make sure the computer logging in is in local area network(lan), or using Google Analytics you need to exclude the
ip comes from lan.

There are two ways to achieve this, one is using regular expression, but in here we will use another method.

Before we start we need to know the private ip range.
10.0.0.0 - 10.255.255.255    
172.16.0.0 - 172.31.255.255  
192.168.0.0 - 192.168.255.255

Then we split ip into 4 sets of numbers, and create 4 varaibles named legit0~3, these variables will be used to
determine whether or not the ip is private.

next is to check ip range, if first set of numbers is equal to 10, then we can check second set of nubmers to see
if the range is in 0~255, and the third and forth set of numbers we can do the same check as first set does, finally
we check legit0 to legit3 variables to see if they are all true, if they are all true it means that the ip we`re 
checking is private ip, and vice versa.

Private ip check function
public bool CheckPrivateIP(string ip)
{
    string[] arrIP;
    List<int> arrNumIP = new List<int>(0);
    bool legit0 = false, legit1 = false, legit2 = false, legit3 = false;
    bool result = true;
    
    arrIP = ip.Split(new string[] { "." }, StringSplitOptions.None);
    for (int i = 0; i < arrIP.Length; i++)
    {
        arrNumIP.Add(int.Parse(arrIP[i]));
    }

    if (arrNumIP[0] == 10)
    {
        legit0 = true;
        if (arrNumIP[1] >= 0 && arrNumIP[1] <= 255) { legit1 = true; }
        if (arrNumIP[2] >= 0 && arrNumIP[2] <= 255) { legit2 = true; }
        if (arrNumIP[3] >= 0 && arrNumIP[3] <= 255) { legit3 = true; }
    }
    else if (arrNumIP[0] == 172)
    {
        legit0 = true;
        if (arrNumIP[1] >= 16 && arrNumIP[1] <= 31) { legit1 = true; }
        if (arrNumIP[2] >= 0 && arrNumIP[2] <= 255) { legit2 = true; }
        if (arrNumIP[3] >= 0 && arrNumIP[3] <= 255) { legit3 = true; }
    }
    else if (arrNumIP[0] == 192)
    {
        legit0 = true;
        if (arrNumIP[1] == 168) { legit1 = true; }
        if (arrNumIP[2] >= 0 && arrNumIP[2] <= 255) { legit2 = true; }
        if (arrNumIP[3] >= 0 && arrNumIP[3] <= 255) { legit3 = true; }
    }

    if (!legit0 || !legit1 || !legit2 || !legit3) { result = false; }

    return result;
}

 
comments powered by Disqus