文章内容
2024/4/22 20:53:50,作 者: 黄兵
通过 Python 判断某个 IP 是否在 IP 地址段中
要判断给定的 IP 地址是否在某个 IP 地址段中,可以使用 ipaddress 模块中的 ip_address 和 ip_network 方法来进行比较。下面是一个示例代码:
import ipaddress
def check_ip_in_ranges(ip, ip_ranges):
ip_address = ipaddress.ip_address(ip)
for ip_range in ip_ranges:
if ip_address in ipaddress.ip_network(ip_range):
return True
return False
ip_ranges = [
"162.142.125.0/24",
"167.94.138.0/24",
"167.94.145.0/24",
"167.94.146.0/24",
"167.248.133.0/24",
"199.45.154.0/24",
"199.45.155.0/24",
"206.168.34.0/24",
"2602:80d:1000:b0cc:e::/80",
"2620:96:e000:b0cc:e::/80",
"2602:80d:1003::/112",
"2602:80d:1004::/112"
]
ip_to_check = "206.168.34.189"
if check_ip_in_ranges(ip_to_check, ip_ranges):
print(f"The IP address {ip_to_check} is in the specified IP ranges.")
else:
print(f"The IP address {ip_to_check} is not in the specified IP ranges.")
这段代码定义了一个函数 check_ip_in_ranges(ip, ip_ranges),它接受一个 IP 地址和 IP 地址段列表作为参数,并检查给定的 IP 地址是否在这些 IP 地址段中。然后,它在主程序中使用给定的 IP 地址来调用这个函数,并输出相应的结果。
评论列表