[英]How can I get the subnet of this IP?
我有這個 IP: 192.168.1.1/24 ,我想得到這個192.168.1.0/24 。 python 中是否有任何內置方法?
所以基本上,有很多屬於“192.0.2.0/28”的 ipadress,如下所示。
for addr in IPv4Network('192.0.2.0/28'):
addr
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
IPv4Address('192.0.2.7')
IPv4Address('192.0.2.8')
IPv4Address('192.0.2.9')
現在我解決了這個問題,但它看起來不太好。
address = "192.168.0.3/28"
network = int(address.split("/")[-1])
new_string = address[:(len(address)-len(str(network))-1)]
last_ip = new_string.split(".")[-1]
first_part = new_string[:(len(new_string)-len(last_ip))]
print(first_part)
txt = str(first_part) + str(last_ip) + "/" + str(network)
print(txt)
print((last_ip))
isRun = True
while isRun:
try:
txt = str(first_part) + str(last_ip) + "/" + str(network)
net4 = ipaddress.ip_network(txt)
print(txt)
isRun = False
except:
last_ip = int(last_ip)
last_ip -= 1
您將需要創建一個IPv4Interface ,然后獲取network
屬性。 或者,如果您知道要檢查的 su.net,則可以使用su.net_of檢查您指定的 .net 是否在另一個 su.net 中。
from ipaddress import IPv4Interface, ip_network
interface_a = IPv4Interface('192.0.2.1/24')
interface_b = IPv4Interface('192.0.2.7/28')
print(interface_a.network)
print(interface_b.network)
a = ip_network('192.0.1.1/24')
b =ip_network('192.0.2.8')
print(b.subnet_of(a))
# outputs
192.168.1.0/24
192.0.2.0/28
True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.