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

前端 未结 3 818
你的背包
你的背包 2021-01-01 07:59

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 diffe

3条回答
  •  梦毁少年i
    2021-01-01 08:34

    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.

提交回复
热议问题