Working with IP Addresses in Python

18 Aug, 2021
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.
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.
Python3
# Import moduleimport ipaddress # Example of valid IPv4 addressprint (ipaddress.ip_address(u'175.198.42.211')) # Invalid IPv4 address raises errorprint (ipaddress.ip_address(u'175.198.42.270'))
Output : 
175.198.42.211 
ValueError: ‘175.198.42.270’ 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.
Python3
# Import moduleimport ipaddress # Example of valid IPv6 addressprint (ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')) # Invalid IPv6 address raises errorprint (ipaddress.ip_address(u'2001:0db8:85a3:0ff0:00000:8a2e:0370:7334'))
Output : 
2001:db8:85a3:2bfe:70d:8a2e:370:7334 
ValueError: ‘2001:0db8:85a3:0ff0:00000:8a2e:0370:7334’ does not appear to be an IPv4 or IPv6 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.
Python3
# Import moduleimport ipaddress # IPv4 addressprint(type(ipaddress.ip_address(u'175.198.42.211')))print(type(ipaddress.ip_address(u'5.0.0.1'))) # IPv6 addressprint(type(ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')))print(type(ipaddress.ip_address(u'0000:f0f0::7b8a:ffff')))
Output : 
<class ‘ipaddress.IPv4Address’> 
<class ‘ipaddress.IPv4Address’> 
<class ‘ipaddress.IPv6Address’> 
<class ‘ipaddress.IPv6Address’> 
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.
Python3
# Import moduleimport ipaddress # Comparisonprint(ipaddress.IPv4Address(u'175.199.42.211') >      ipaddress.IPv4Address(u'175.198.42.255')) print(ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')      == ipaddress.IPv6Address(u'2001:0dff:85a3:2bfe:070d:8a2e:0370:7334')) print(ipaddress.IPv4Address(u'179.198.42.211') !=      ipaddress.IPv4Address(u'175.198.42.255')) print(ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334') <      ipaddress.IPv6Address(u'2001:0dff:85a3:2bfe:070d:8a2e:0370:7334'))
Output :
True 
False 
True 
True 
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.
Python3
# Import moduleimport ipaddress # Arithmetic Operation on IPv4 addressprint(ipaddress.IPv4Address(u'129.117.0.0')-6)print (ipaddress.IPv4Address(u'175.199.42.211')+55)print (ipaddress.IPv4Address(u'0.0.0.0')-1)print (ipaddress.IPv4Address(u'255.255.255.255')+1) # Arithmetic Operation on IPv6 addressprint (ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')-330)print (ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')+1000)print (ipaddress.IPv6Address(u'0000::0000')-1)print (ipaddress.IPv6Address(u'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')+1)
Output : 
129.116.255.250 
175.199.43.10 
AddressValueError: -1 (< 0) is not permitted as an IPv4 address
 AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address 
2001:db8:85a3:2bfe:70d:8a2e:370:71ea 
2001:db8:85a3:2bfe:70d:8a2e:370:771c 
AddressValueError: -1 (< 0) is not permitted as an IPv6 address 
AddressValueError: 340282366920938463463374607431768211456 (>= 2**128) is not permitted as an IPv6 address 
 
arorakashish0911
Python-Networking
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list