I know how to get all the IP in range
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.
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
How can I get that in python?
You can use 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
.
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:
- for IPv4, the network and broadcast addresses are always excluded. For subnets that contains less than 4 IP addresses /31 and /32 report in a manner per RFC 3021
RFC 3021 says:
In a point-to-point link with a 31-bit subnet mask, the two addresses above MUST be interpreted as host addresses.
So both ip addresses with a mask of 255.255.255.254
are reported:
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')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.