思路:
1.将2个ip都转换成整数,将子网掩码也转换成整数;
2.把两个ip的整数都和子网掩码整数进行&操作
3.最后比较两个&值,相同则为同网段,否则为不同网段
代码:
v4:
ip_1_int = int(ipaddress.IPv4Address(ip_1))
ip_2_int = int(ipaddress.IPv4Address(ip_2))
prefix_int = 0xffffffff << (32 - prefix)
is_same = (ip_1_int & prefix_int) == (ip_2_int & prefix_int)
v6:
ip_1_int = int(ipaddress.IPv6Address(ip_1))
ip_2_int = int(ipaddress.IPv6Address(ip_2))
prefix_int = 0xffff ffff ffff ffff ffff ffff ffff ffff << (128 - prefix)
is_same = (ip_1_int & prefix_int) == (ip_2_int & prefix_int)