Compare two ip subnet

2.2k Views Asked by At

How to decide if two ip are on the same subnet or not? The only input is the ip address and the subnet mask! What is the optimal way, using C/C++, to compute if two ip have the same subnet?

3

There are 3 best solutions below

1
On BEST ANSWER
bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {
   return (ipA & subnetMask) == (ipB & subnetMask);
}
10
On
typedef unsigned char BYTE;

Bool CheckForSubnetParity(
BYTE[] _In_ iPAddress1, 
BYTE[] _In_ iPAddress2, 
BYTE[] _In_ subNetMask
) {

      BYTE[] NetworkPrefix1 = new BYTE[4];
      BYTE[] NetWorkPrefix2 = new BYTE[4];
      Bool Result = true;

      for ( int x = 0; x < 4; x++) 
      {
          NetworkPrefix1[x] = iPAddress1[x] && subNetMask[x];
          NetworkPrefix2[x] = iPAddress2[x] && subNetMask[x];
          if ( NetworkPrefix1[x] != NetworkPrefix2[x] ) 
          {
              Result = false;
          }
      }

      return Result;
   }
1
On

You can apply 'xor' operation to both IP's using their mask and compare them after that. If they're identical, then both IP addresses in the same subnet.

Let's look at the 172.16.2.4/255.255.0.0 and 172.16.1.69/255.255.0.0 After 'xor' you'll get '172.16.0.0' for both addresses, so they are in the same subnet.

Regards.