[英]How can I get the subnet of this IP?
I have this IP: 192.168.1.1/24 , and I would like to get this 192.168.1.0/24 .我有这个 IP: 192.168.1.1/24 ,我想得到这个192.168.1.0/24 。 Is there any built in method for this in python?
python 中是否有任何内置方法?
so basically, there are lots of ipadress belonging to '192.0.2.0/28" as you can see below.所以基本上,有很多属于“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')
now I solved this problem, but it doesnt looks nicely.现在我解决了这个问题,但它看起来不太好。
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
You will need to create an IPv4Interface then get the get the network
attribute.您将需要创建一个IPv4Interface ,然后获取
network
属性。 Alterantively, if you know the su.net you want to check against you could use su.net_of to check if the.network you specify is in the su.net of the other.或者,如果您知道要检查的 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.