How to know if given IPV6 address belongs to the same subnet as local machine

帅比萌擦擦* 提交于 2020-01-07 07:45:10

问题


Currenly I have a c function that takes a ip address and subnetmask and checks if given ipv4 is private/public.

It does by following logic to matchsubnet:

(local ipv4 address && local subnetmask) == (given ipv4 && given subnetmask)

What logic can be written for ipv6? I can write a function to receive an ip and subnet prefix. Can i get local subnet prefix?


回答1:


I order to determine if two hosts are on the same subnet take both their addresses and prefix lengths (subnet masks).

If the prefix lengths are different then they are not on the same network.

If the prefix lengths are the same then take the length ( very probably 64, so let's assume that) and compare the first 64 bits of both addresses with each other. If they are the same then they are both on the same network.

It is basically the same as you do for IPv4 with making the bits that don't being to the prefix. With 128 addresses it might be easier though to implement it as a loop comparing 4 bits at a time (comparing the hexadecimal notation) or 8 bits at a time (comparing the parsed bytes).



来源:https://stackoverflow.com/questions/37613704/how-to-know-if-given-ipv6-address-belongs-to-the-same-subnet-as-local-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!