简体   繁体   中英

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

Currenly I have ac 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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM