IP network objects

Let's import the ipaddress module and define a net4 network:

>>> import ipaddress
>>> net4 = ipaddress.ip_network('10.0.1.0/24')

Now, we can find some useful information, such as netmask and the network/broadcast address, of net4:

>>> net4.netmask
IP4Address(255.255.255.0)

The netmask properties of net4 will be displayed as an IP4Address object. If you are looking for its string representation, then you can call the str() method, as shown here:

>>> str(net4.netmask)
'255.255.255.0'

Similarly, you can find the network and the broadcast addresses of net4 by using the following code:

>>> str(net4.network_address)
10.0.1.0
>>> str(net4.broadcast_address)
10.0.1.255

We can get the number of addresses net4 can hold with the following command:

>>> net4.num_addresses
256

So, if we subtract the network and the broadcast addresses, the total available IP addresses will be 254. We can call the hosts() method on the net4 object. This will produce a Python generator, which will supply all the hosts as IPv4Address objects:

>>> net4.hosts()
>>> <generator object _BaseNetwork.hosts at 0x02F25FC0>
>>> all_hosts = list(net4.hosts())
>>> len(all_hosts)
254
>>> print(all_hosts)
>>> [IPv4Address('10.0.1.1'), IPv4Address('10.0.1.2'), IPv4Address('10.0.1.3'), IPv4Address('10.0.1.4'),......,IPv4Address('10.0.1.253'), IPv4Address('10.0.1.254')]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset