Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether two IP addresses belong to the same network segment

Tags:

ip-address

An easy question often puzzled me: There are two IP(v4) addresses,192.168.0.1/30 and 192.168.0.2/24, I wonder whether they belong to the same network segment.

How do you determine that?

like image 868
danspeed Avatar asked Oct 11 '22 07:10

danspeed


1 Answers

The /24 signifies the number of bits which make up the network portion of the address, in this case 24 (or 30).

If you AND the IP address with the smallest network portion only, identical networks will contain the same value.

For instance, here is a C implementation (untested):

unsigned int ip1 = (192<<24) | (168<<16) | (0<<8) | (1);
unsigned int ip2 = (192<<24) | (168<<16) | (0<<8) | (2);
unsigned int nm1 = (-1) << (32 - 24);
ip1 &= nm1; // Note: we use nm1 as its the smallest number of bits in the network
ip2 &= nm1;
if (ip1 == ip2) { }  // Same network

Technically, your /30 and /24 are different networks, and will use routers to reach different addresses (i.e., the /24 will not use a router for IP's 1-254, while the /30 will use a router for most of those addresses). However, they overlap in the same address space.

like image 87
Yann Ramin Avatar answered Nov 16 '22 17:11

Yann Ramin