Convert IP to Integer and Integer To IP in Python
Python provides ipaddress, a built-in module that allows to create, manipulate, and operate on IPv4 and IPv6 addresses and networks.
The classes and functions in the IP address module make it simple to perform a variety of IP address-related tasks, such as determining whether two hosts are on the same subnet, iterating over all hosts in a given subnet, determining whether a string represents a valid IP address or network definition, and so on.
The following example code uses Python's ipaddress module to convert IPv4/IPv6 to integer:
import ipaddress
def ip_to_integer(string_ip):
try:
if type(ipaddress.ip_address(string_ip)) is ipaddress.IPv4Address:
return int(ipaddress.IPv4Address(string_ip))
if type(ipaddress.ip_address(string_ip)) is ipaddress.IPv6Address:
return int(ipaddress.IPv6Address(string_ip))
except Exception as e:
return -1
To convert integer IP back to IPv4/IPv6, you can use the Python's ipaddress module as follows:
import ipaddress
def integer_to_ip(int_ip):
return ipaddress.ip_address(int_ip).__str__()
Here is the complete running code:
import ipaddress
def ip_to_integer(string_ip):
try:
if type(ipaddress.ip_address(string_ip)) is ipaddress.IPv4Address:
return int(ipaddress.IPv4Address(string_ip))
if type(ipaddress.ip_address(string_ip)) is ipaddress.IPv6Address:
return int(ipaddress.IPv6Address(string_ip))
except Exception as e:
return -1
def integer_to_ip(int_ip):
return ipaddress.ip_address(int_ip).__str__()
# convert ip to integer
ip = "192.23.3.2"
ip_integer = ip_to_integer(ip)
print("The integer representation of %s ip is %s" % (ip, ip_integer))
# converting ip integer back to ip
original_ip = integer_to_ip(ip_integer)
print("Converting %s ip integer back to ip %s" % (ip_integer, original_ip))
The above code gives the following output:
Converting 3222733570 ip integer back to ip 192.23.3.2
You may also be interested in learning how to get IPv4/IPv6 Address Range from CIDR in Python