Determining if two IP adresses are on same subnet – is it leading or trailing 0s get dropped from IP address

ip addressmathnetworkingsubnet

I understand if two IP addresses are AND'd with a subnet mask if the result is the same then they are on the same network. If the result is different then they are on different networks. My question is, when given an IP address omitting some 0s where do the extra 0s get placed?

For example if the subnet mask is 255 . 128 . 0 . 0 , and you have IP 126 . 1 . 0 . 10 and IP 126 . 127 . 0 . 1 if you just blindly AND the IPs with the subnet mask you get different results even though they are on the same network.

Does 126.1.0.10 become 126.100.000.100 or 126.001.000.100?

EDIT after reading replies:

255128000000 AND 126001000010 = 1085496376*32* but 255128000000 AND 126127000001 = 1085276323*84*
Am I missing something?

Best Answer

IPv4 addreses are written as four ordinary decimal numbers (each fitting into a byte) separated by dots.

The ordinary decimal number 1 is "one", which can also be written 001. However 100 is a different number, namely "a hundred".


The AND operation is always a bitwise AND, so to understand it you must first see how the dotted-decimal address and netmask corresponds to a raw binary 32-bit address:

        126   .    127   .     0    .    1
     01111110   01111111   00000000   00000001

        255   .    128   .     0    .    0
AND  11111111   10000000   00000000   00000000
 -----------------------------------------------
     01111110   00000000   00000000   00000000
        126   .      0   .     0    .    0

So 126.127.0.1 with netmask 255.128.0.0 is in subnet 126.0.0.0/9

In software one usually stores IPv4 addresses in a single 32-bit variable -- so 126.127.0.1 is 01111110011111110000000000000001 binary (which also encodes 2122252289 decimal, except that nobody ever cares what the decimal value of a 32-bit IP address is), and it is converted to dotted-decimal only when it needs to be shown to human users. This representation is what glglgl decribes as multiplying by 256 several times.

If you also have the netmask in a 32-bit variable (11111111100000000000000000000000 binary or 4286578688 decimal), you can AND them in a single machine instruction to get the network address 01111110000000000000000000000000.

Related Topic