Geeks With Blogs

News The Code Project

I am from Munshigonj, Bangladesh. For me, programming is a passion first, a hobby second, and a career third. My Primary Blog:

Razan Paul Blog Explaining thoughts and findings is a great way to learn

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:    }
  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.

Posted on Friday, September 18, 2009 8:05 PM | Back to top

Comments on this post: Testing whether two IP addresses are in the same network using c#.

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Razan | Powered by: