VOOZH about

URL: https://www.geeksforgeeks.org/python/convert-ip-address-to-integer-and-vice-versa/

⇱ Convert IP Address to Integer and Vice Versa - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert IP Address to Integer and Vice Versa

Last Updated : 14 Jan, 2026

Given an IP address in dotted-decimal format (IPv4), the task is to convert it into its corresponding integer value and also convert an integer back into an IP address. For Example:

Input: IP Address -> 192.168.1.1
Output: Integer -> 3232235777

Reverse Input: 3232235777
Reverse Output: IP Address -> 192.168.1.1

ipaddress.ip_address()

ipaddress.ip_address() creates and validates an IP address object from a string or an integer. Below is the syntax:

ipaddress.ip_address(address)

  • Parameter:address - IP address as a string (e.g., "192.168.1.1") or an integer (values < 2**32 are treated as IPv4)
  • Returns: An IPv4Address or IPv6Address object
  • Error: Raises ValueError if the IP address is not valid

IP Address to Integer

In this example, an IP address is converted into its numeric (integer) form using the ipaddress module.


Output
3221225000
123
42540766400282592856903984001653826561

Integer to IP Address

In this example, integer values are converted back into readable IPv4 and IPv6 addresses.


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

Need for Converting IP Addresses to Integers

The following points explain why IP addresses are often converted into integer form:

  • Allows IP addresses to be stored in databases as numeric values.
  • Makes it easier to compare IP addresses (greater, smaller, range checking).
  • Helps in sorting and indexing IP addresses efficiently.
  • Useful for network calculations like finding IP ranges and subnet limits.
  • Required by some networking and socket operations that work with numeric IP values.

Related Articles:

Comment