如何知道给定的IPV6地址是否与本地计算机属于同一子网 [英] How to know if given IPV6 address belongs to the same subnet as local machine

查看:176
本文介绍了如何知道给定的IPV6地址是否与本地计算机属于同一子网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个c函数,该函数接受一个ip地址和子网掩码,并检查给定的ipv4是否为私有/公共.

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)

可以为ipv6编写什么逻辑?我可以编写一个函数来接收ip和子网前缀.我可以获取本地子网前缀吗?

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.

如果前缀长度相同,则取该长度(很可能为64,因此我们假设为该长度),并将两个地址的前64位彼此进行比较.如果它们相同,则它们都在同一网络上.

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.

与IPv4基本上相同,只是不添加前缀.有了128个地址,将它实现为一次比较4位(比较十六进制表示法)或一次8位(比较已解析的字节)的循环可能会更容易.

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

这篇关于如何知道给定的IPV6地址是否与本地计算机属于同一子网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆