Python程序查找两个IP地址是否属于相同或不同的网络
先决条件:无类域间路由 (CIDR)
给定 CIDR 表示法中的两个 IP 地址,确定它们属于同一网络还是不同网络。如果两个 IP 地址的网络 ID 相同,则称两个 IP 地址在同一网络中。
例子:
Input : IP1 = 192.168.1.0/8, IP2 = 192.32.45.7/8
Output : Same Network
Explanation : The number of bits in Network ID of both the IP Addresses is 8 bits and the first
8 bits (i.e 1st octet) of both the IP Addresses is same (i.e 192). Hence both IP Addresses
belong to Same Network.
Input : IP1 = 17.53.128.0/20, IP2 = 17.53.127.0/20
Output : Different Network
Explanation : The number of bits in Network ID of both the IP Addresses is 20 bits but the first
20 bits of both the IP Addresses are different. Hence both IP Addresses belong to Different
Network.
为了实现它,我们将使用Python 3.3 的 ipaddress 模块的ip_network和network_address方法。
# importing ip_network from ipaddress module
from ipaddress import ip_network
def sameNetwork(IP1: str, IP2: str) -> str:
a = ip_network(IP1, strict = False).network_address
b = ip_network(IP2, strict = False).network_address
if(a == b) :
return "Same Network"
else :
return "Different Network"
# main function
if __name__ == '__main__' :
# Same Network
print(sameNetwork('192.168.1.0/8', '192.32.45.7/8'))
# Different Network
print(sameNetwork('17.53.128.0/20', '17.53.127.0/20'))
输出 :
Same Network
Different Network