Sunday, November 17, 2024
Google search engine
HomeLanguagesConvert IP address to integer and vice versa

Convert IP address to integer and vice versa

We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks.

The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) usually won’t accept objects from ipaddress module directly. Instead, they must be converted to string or an integer that the other module will accept.

Syntax: ipaddress.ip_address(address)

Parameter: Passing IP address in form of integer or string. Integers value less than 2**32 are considered as IPv4 addresses.

Returns: IPv4Address or IPv6Address object is returned depending on the IP address passed as argument. If address passed does not represent a valid IPv4 or IPv6 address, a ValueError is raised.

Program to convert integers to IP Address : 

Python3




# importing the module
import ipaddress
  
# converting int to IPv4 address
print(ipaddress.ip_address(3221225000))
print(ipaddress.ip_address(123))
  
# converting int to IPv6 address
print(ipaddress.ip_address(42540766400282592856903984001653826561))


Output:

191.255.254.40
0.0.0.123
2001:db7:dc75:365:220a:7c84:d796:6401

For converting IP addresses to integers: 

Python3




# importing the module
import ipaddress
  
# converting IPv4 address to int
addr1 = ipaddress.ip_address('191.255.254.40')
addr2 = ipaddress.ip_address('0.0.0.123')
print(int(addr1))
print(int(addr2))
  
# converting IPv6 address to int
addr3 = ipaddress.ip_address('2001:db7:dc75:365:220a:7c84:d796:6401')
print(int(addr3))


Output:

3221225000
123
42540766400282592856903984001653826561
RELATED ARTICLES

Most Popular

Recent Comments