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

前端 未结 3 816
你的背包
你的背包 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条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 08:56

    You are completely missing something: You don't just concat your digits together, because AND works on binary level.

    So either you process the IPv4 addresses byte-wise, or you transform them into a decimal number, but not with factor 1000, but with factor 256.

    This is to say, instead of doing

    ((126 * 1000 + 1) * 1000 + 0) * 1000 + 10 = 126001000010
    

    you should do

    ((126 * 256 + 1) * 256 + 0) * 256 + 10 = 2113994762
    

    . If you apply this to the other numbers, you should succeed.

    Alternatively, you could AND together the 4 numbers separately, so

    255 & 126 = 126 (in both cases), 128 & (1 resp. 127) = 0, 0 & (anything) = 0, 0 & (anything) = 0.
    

    So you get 126.0.0.0 for both, making them belong to the same subnet.

提交回复
热议问题