The Python ipaddress module

The ipaddress module simplifies working with IPv4 and IPv6 addresses in Python. In this section, we will focus on IPv4 and will work primarily with the following three class types:

  • IPv4Address: Represents a single IPv4 address
  • IPv4Network: Represents an IPv4 network
  • IPv4Interface: Represents an IPv4 interface

You can get more information about this module with the help command from the Python interpreter:

IPv4Address is the class that represents and manipulates single IPv4 addresses:

The class represents an IPv4 address or network. To create these objects in Python, the module provides some basic factory functions:

import ipaddress
from ipaddress import IPv4Address, IPv4Network, IPv4Interface

After you create an IPv4/IPv6 object, you can get a lot information from the class, for example, whether it is a multicast address or a private address, the prefix length, and netmask.

In the following screenshot, we can see the methods that are used to check these use cases:

From Python 3.3, the best way to check whether an IPv6 or IPv4 address is correct is to use the Python standard library module, ipaddress.

Check out https://docs.python.org/3/library/ipaddress.html for the complete documentation.

If you're using Python 3.3 or later, you can use the ipaddress module to validate the IP address:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('500.500.0.1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/ipaddress.py", line 54, in ip_address
address)
ValueError: '500.500.0.1' does not appear to be an IPv4 or IPv6 address

In this example, we use this method to validate both IPv4 and IPv6. You can find the following code in the validate_ip_address.py file:

!/usr/bin/env python3

import ipaddress
import sys

try:
ip = ipaddress.ip_address(sys.argv[1])
print('%s is a correct IP%s address' % (ip, ip.version))
except ValueError:
print('address/netmask is invalid: %s' % sys.argv[1])
except:
print('Usage : %s ip' % sys.argv[0])

If you execute the previous script with an IP address as a parameter, it will validate in both IPv4 and IPv6 versions:

$ python validate_ip_address.py 127.0.0.1
127.0.0.1 is a correct IP4 address
$ python validate_ip_address.py ::1
::1 is a correct IP6 address
..................Content has been hidden....................

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