Testing whether two IP addresses are in the same network using c#.

IPv4 address has two basic parts:  the network part and the host part. As we know, if network potions of two IPs are same, they are in the same network. By performing and operation between subnet mask and IP address, we can get the network portion of an IP. By this way, we have found the network portions of two IPs. Then just check whether the network portions are equal or not. For this the following code is written:

   1: private static bool CheckWhetherInSameNetwork(string firstIP, string subNet, string secondIP )
   2:    {
   3:        uint subnetmaskInInt = ConvertIPToUint(subNet);
   4:        uint firstIPInInt = ConvertIPToUint(firstIP);
   5:        uint secondIPInInt = ConvertIPToUint(secondIP);
   6:        uint networkPortionofFirstIP = firstIPInInt & subnetmaskInInt;
   7:        uint networkPortionofSecondIP = secondIPInInt & subnetmaskInInt;
   8:        if (networkPortionofFirstIP == networkPortionofSecondIP)
   9:            return true;
  10:        else
  11:            return false;
  12:    }
  13:  
  14:    static public uint ConvertIPToUint(string ipAddress)
  15:    {
  16:        System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ipAddress);
  17:        byte[] byteIP = iPAddress.GetAddressBytes();
  18:        uint ipInUint = (uint)byteIP[3] << 24;
  19:        ipInUint += (uint)byteIP[2] << 16;
  20:        ipInUint += (uint)byteIP[1] << 8;
  21:        ipInUint += (uint)byteIP[0];
  22:        return ipInUint;
  23:    }

Hope this will save some of your time.

No Comments