Skip to content
Related Articles

Related Articles

Convert IP address to integer and vice versa
  • Last Updated : 01 Nov, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

For converting IP addresses to integers: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

3221225000
123
42540766400282592856903984001653826561

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :