[英]All ip in range of subnet-mask
I know how to get all the IP in range 我知道如何获得范围内的所有IP
from netaddr import iter_iprange
generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)
What I want is get all the Ip that fix to subnet mask with some IP. 我想要的是获得所有用一些IP修复子网掩码的IP。
For example I get Ip 2.2.2.2 and mask 255:255:255:0 so I neet to get 255 ip adrresses 2.2.2.2 - 2.2.2.255 , but if subnetmask is 255.255.255.254 I there is no IP that fix to this 例如,我得到Ip 2.2.2.2和掩码255:255:255:0所以我得到255个IP地址2.2.2.2 - 2.2.2.255,但如果子网掩码是255.255.255.254我没有修复此问题的IP
How can I get that in python? 我怎么能在python中得到它?
You can use IPNetwork: 您可以使用IPNetwork:
from netaddr import IPNetwork
ip_addr = '2.2.2.2'
mask = '255.255.255.0'
network = IPNetwork('/'.join([ip_addr, mask]))
generator = network.iter_hosts()
Note: 2.2.2.2/255.255.255.0
is equivalent to CIDR 2.2.2.0/24
, both work for IPNetwork
. 注意:
2.2.2.2/255.255.255.0
相当于CIDR 2.2.2.0/24
,两者都适用于IPNetwork
。
Converting to a list you get: 转换为您获得的列表:
In []:
list(generator)
Out[]:
[IPAddress('2.2.2.1'),
IPAddress('2.2.2.2'),
IPAddress('2.2.2.3'),
...
IPAddress('2.2.2.252'),
IPAddress('2.2.2.253'),
IPAddress('2.2.2.254')]
According to the netaddr.iter_host
documentation: 根据
netaddr.iter_host
文档:
- for IPv4, the network and broadcast addresses are always excluded.
对于IPv4,始终排除网络和广播地址。 For subnets that contains less than 4 IP addresses /31 and /32 report in a manner per RFC 3021
对于包含少于4个IP地址/ 31和/ 32的子网,按照RFC 3021的方式报告
RFC 3021 says: RFC 3021说:
In a point-to-point link with a 31-bit subnet mask, the two addresses above MUST be interpreted as host addresses.
在具有31位子网掩码的点对点链路中,上面的两个地址必须被解释为主机地址。
So both ip addresses with a mask of 255.255.255.254
are reported: 因此报告了两个掩码为
255.255.255.254
IP地址:
In []:
mask = '255.255.255.254'
list(IPNetwork('/'.join([ip_addr, mask])).iter_hosts())
Out[]:
[IPAddress('2.2.2.2'), IPAddress('2.2.2.3')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.