从IP地址获取子网 [英] Get subnet from IP address

查看:114
本文介绍了从IP地址获取子网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取我拥有的IP地址的子网.

I am trying to get subnet for IP address I have.

例如:

1

子网掩码:255.255.255.0

输入:192.178.2.55

输出:192.178.2.0

2

子网掩码:255.255.0.0

输入:192.178.2.55

输出:192.178.0.0

目前,我的操作方式(对于子网255.255.255.0)

Currently, the way I do it (for subnet 255.255.255.0)

ip =  '192.178.2.55'
subnet = '.'.join(ip.split('.')[:2]) + '.0.0'
subnet
'192.178.0.0'

我看到python具有 ipaddress 库.但是我找不到能完成上述任务的方法.

I see python has ipaddress library. However I could not find a method that could do the above task.

奖金:由于 ipaddress 支持IPv4和IPv6,因此如果两者都可以使用相同的功能.

Bonus : Since ipaddress supports IPv4 and IPv6, if the same function could be used for both.

推荐答案

ipaddress.ip_network 函数可以采用IPv4NetworkIPv6Network可以采用的任何字符串格式,包括address/mask格式.

The ipaddress.ip_network function can take any of the string formats that IPv4Network and IPv6Network can take, including the address/mask format.

由于您实际上没有传递网络地址,而是传递了设置了主机位的该网络中的地址,因此您需要使用strict=False.

Since you're not actually passing the network address, but an address within that network with host bits set, you need to use strict=False.

所以:

>>> net = ipaddress.ip_network('192.178.2.55/255.255.255.0', strict=False)
>>> net
IPv4Network('192.178.2.0/24')
>>> net.network_address
IPv4Address('192.178.2.0')
>>> net.netmask
IPv4Address('255.255.255.0')


或者,您可以使用 ip_interface 并提取从那里开始的网络:


Alternatively, you can use ip_interface and extract the network from there:

>>> iface = ipaddress.ip_interface('192.178.2.55/255.255.255.0')
>>> iface
IPv4Interface('192.178.2.55/24')
>>> iface.network
IPv4Network('192.178.2.0/24')
>>> iface.netmask
IPv4Address('255.255.255.0')
>>> iface.ip
IPv4Address('192.178.2.55')
>>> iface.network.network_address
IPv4Address('192.178.2.0')


您要选择哪两个取决于您要表达的内容.注意,接口类型是地址类型的子类,它们当然会记住用于构造它们的原始地址,而网络类会记住网络地址.这两个因素之一通常是决定因素.


Which of the two you want depends on what exactly you're trying to represent. Notice that the Interface types are subclasses of the Address types, and of course they remember the original address that was used to construct them, while the Network classes remember the network address; one of those two is usually the deciding factor.

当然,它们两者都可以与IPv6一起使用:

Both of them will, of course, work just as well with IPv6:

>>> ipaddress.ip_interface('2001:db8::1000/32')
IPv6Interface('2001:db8::1000/32')
>>> ipaddress.ip_interface('2001:db8::1000/32').network.network_address
IPv6Address('2001:db8::')

这篇关于从IP地址获取子网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆