Geeks With Blogs

News

I am from Munshigonj, Bangladesh. For me, programming is a passion first, a hobby second, and a career third. My Primary Blog: http://weblogs.asp.net/razan/
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:    }`
`  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.

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