Given an IP address of a host and its CIDR (for instance, 143.204.181.28 and 143.204.176.0/21 respectively), is it possible to get a subnet ID in which the host belongs and a range of IP addresses belonging to the same subnet? If it is possible, I will appreciate if somebody provides a python code demonstrating how to achieve this.
You could use built-in module ipaddress
( doc ):
import ipaddress
addr = ipaddress.ip_address('143.204.181.28')
net = ipaddress.ip_network('143.204.176.0/21')
for s in net.subnets():
if addr in s:
print('subnet:', s)
ips = [*s]
print('Subnet contains {} IPs'.format(len(ips)))
Prints:
subnet: 143.204.180.0/22
Subnet contains 1024 IPs
The IPs are in variable ips
.
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.