0
votes

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.

1

1 Answers

0
votes

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.