IP (Internet Protocol) -Address is the basic fundamental concept of computer networks which provides the address assigning capabilities to a network. Python provides ipaddress module which is used to validate and categorize the IP address according to their types(IPv4 or IPv6). This module is also used for performing wide range of operation like arithmetic, comparison, etc to manipulate the IP addresses.
Validating IP Addresses-
For validating IP addresses python uses ip_address() function provided by the ipaddress module which raises error if values of IP exceeds the range of the type of the IP address.
- IPv4 : It is a 32-bit number typically written in decimal digits formatted as four 8-bit numbers separated by dots, is used to identify the network interface of a machine. The ip_address() function throws an error if the range value exceeds from 0 to 255.
ValueError: ‘220.127.116.110’ does not appear to be an IPv4 or IPv6 address
- IPv6 : It is represented by eight groups of four hexadecimal digits separated by colons, where each group represents 16 bits, two octets also known as hextet. The ip_address() function throws an error if the range value exceeds from 0 to FFFF.
ValueError: ‘2001:0db8:85a3:0ff0:00000:8a2e:0370:7334’ does not appear to be an IPv4 or IPv6 address
Operations on IP Address-
Various operations like arithmetic, comparison, type, etc can be performed on the IP addresses with the help of ipaddress module. Some operations are listed below:
- Type Check operation : The type() method takes various formats of IP addresses as input and recognizes whether it is IPv4 or IPv6 address, indicating the category of the IP address.
- IP Comparison Operations : The basic logical operators can be used to compare the IP addresses, whether one value is equal or greater or less than the other.
- Arithmetic Operations : IP Addresses can be manipulated by performing some arithmetic operations. Integers can be added or subtracted from the IP addresses. Under addition if value of last octet exceeds 255 then previous octet is incremented and so on, same in the case of subtraction if the value of the last octet becomes less than zero, then the previous octet is decremented and so on.
AddressValueError: -1 (< 0) is not permitted as an IPv4 address
AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
AddressValueError: -1 (< 0) is not permitted as an IPv6 address
AddressValueError: 340282366920938463463374607431768211456 (>= 2**128) is not permitted as an IPv6 address
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course