You need to mask the two addresses with the same network mask in order to determine if the network is the same. You need to use the shortest network mask for the comparison. This is how you determine whether or not both addresses are in the same network.
The procedure is exactly the same for both IPv4 and IPv6, except for the address and mask sizes.
For example, 10.0.0.0/25
and 10.0.0.64/26
will retrun the same network with the shortest mask (255.255.255.128
), but will return different networks with the longest mask (255.255.255.192
) even though the second network is a subnet of the first network, so any addresses in the second network fall into the first network.
With the shortest mask:
10.0.0.0 -> 00001010000000000000000000000000
255.255.255.128 -> 11111111111111111111111110000000
AND -> ================================
00001010000000000000000000000000 = 10.0.0.0
10.0.0.64 -> 00001010000000000000000001000000
255.255.255.128 -> 11111111111111111111111110000000
AND -> ================================
00001010000000000000000000000000 = 10.0.0.0
With the longest mask:
10.0.0.0 -> 00001010000000000000000000000000
255.255.255.192 -> 11111111111111111111111111000000
AND -> ================================
00001010000000000000000000000000 = 10.0.0.0
10.0.0.64 -> 00001010000000000000000001000000
255.255.255.192 -> 11111111111111111111111111000000
AND -> ================================
00001010000000000000000001000000 = 10.0.0.64
With the assigned masks:
10.0.0.0 -> 00001010000000000000000000000000
255.255.255.128 -> 11111111111111111111111110000000
AND -> ================================
00001010000000000000000000000000 = 10.0.0.0
10.0.0.64 -> 00001010000000000000000001000000
255.255.255.192 -> 11111111111111111111111111000000
AND -> ================================
00001010000000000000000001000000 = 10.0.0.64
As you can see, only the example using the shortest mask actually returns the correct answer that the second address is in the network of the first address.