Last modified: Sep 13, 2026

Python Convert IP Address to Integer

Converting an IP address to an integer in Python is a common task in networking applications. This conversion helps in efficient storage and comparison of IP addresses. In this article, we'll explore different methods to achieve this conversion effectively.

Why Convert IP Addresses to Integers?

IP addresses are typically represented as strings (e.g., "192.168.1.1"). However, storing them as integers offers several advantages:

  • Faster comparisons between IP addresses
  • Efficient database indexing and storage
  • Easier range queries for network analysis

Let's dive into the methods used to perform this conversion in Python.

Method 1: Using the ipaddress Module

Python provides a built-in module called ipaddress that simplifies working with IP addresses. This module includes functions to convert IP addresses to integers seamlessly.


import ipaddress

# Define an IP address
ip_str = "192.168.1.1"

# Convert to IPv4Address object
ip_obj = ipaddress.ip_address(ip_str)

# Convert to integer
ip_int = int(ip_obj)

print(f"IP Address: {ip_str}")
print(f"Integer: {ip_int}")

IP Address: 192.168.1.1
Integer: 3232235777

This method is clean and handles both IPv4 and IPv6 addresses automatically. The int() function converts the IP object directly to its integer representation.

Method 2: Manual Conversion for IPv4

If you prefer understanding the underlying logic, you can manually convert an IPv4 address to an integer. Here's how:


def ip_to_int(ip_address):
    # Split the IP address into octets
    octets = ip_address.split('.')
    
    # Convert each octet to integer and apply bit shifting
    result = 0
    for i, octet in enumerate(octets):
        result += int(octet) << (8 * (3 - i))
    
    return result

# Example usage
ip_str = "192.168.1.1"
ip_int = ip_to_int(ip_str)

print(f"IP Address: {ip_str}")
print(f"Integer: {ip_int}")

IP Address: 192.168.1.1
Integer: 3232235777

In this method, each octet is shifted left by a multiple of 8 bits. The first octet is shifted by 24 bits, the second by 16 bits, and so on. This creates a unique integer representation of the IP address.

Method 3: Using socket.inet_aton

The socket module provides another way to convert IP addresses. The inet_aton function converts an IP address to a packed 32-bit format.


import socket
import struct

def ip_to_int_socket(ip_address):
    # Convert IP to packed format
    packed_ip = socket.inet_aton(ip_address)
    
    # Unpack as unsigned integer
    ip_int = struct.unpack("!I", packed_ip)[0]
    
    return ip_int

# Example usage
ip_str = "192.168.1.1"
ip_int = ip_to_int_socket(ip_str)

print(f"IP Address: {ip_str}")
print(f"Integer: {ip_int}")

IP Address: 192.168.1.1
Integer: 3232235777

This approach uses struct.unpack to interpret the packed bytes as an unsigned integer. The "!" prefix ensures network byte order (big-endian).

Converting Back: Integer to IP Address

Sometimes you need to convert the integer back to an IP address. Here are methods to do both conversions:


import ipaddress

# Integer to IP using ipaddress module
ip_int = 3232235777
ip_obj = ipaddress.ip_address(ip_int)
print(f"Integer: {ip_int}")
print(f"IP Address: {ip_obj}")

# Manual conversion back for IPv4
def int_to_ip(ip_int):
    # Extract each octet using bit masking
    octet1 = (ip_int >> 24) & 0xFF
    octet2 = (ip_int >> 16) & 0xFF
    octet3 = (ip_int >> 8) & 0xFF
    octet4 = ip_int & 0xFF
    
    return f"{octet1}.{octet2}.{octet3}.{octet4}"

# Example usage
original_ip = "192.168.1.1"
converted_int = ip_to_int(original_ip)
back_to_ip = int_to_ip(converted_int)

print(f"Original IP: {original_ip}")
print(f"Converted to int: {converted_int}")
print(f"Back to IP: {back_to_ip}")

Integer: 3232235777
IP Address: 192.168.1.1
Original IP: 192.168.1.1
Converted to int: 3232235777
Back to IP: 192.168.1.1

Handling IPv6 Addresses

The ipaddress module also supports IPv6 addresses. IPv6 addresses are longer and produce much larger integers:


import ipaddress

# IPv6 address conversion
ipv6_str = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
ipv6_obj = ipaddress.ip_address(ipv6_str)
ipv6_int = int(ipv6_obj)

print(f"IPv6 Address: {ipv6_str}")
print(f"Integer: {ipv6_int}")
print(f"Hex: {hex(ipv6_int)}")

IPv6 Address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
Integer: 42540488161975842760550356425300246516
Hex: 0x20010db885a3000000008a2e03707334

Common Use Cases

Here are some practical scenarios where IP-to-integer conversion proves useful:

  1. Database Indexing: Storing IPs as integers improves query performance
  2. Range Queries: Easily find IPs within specific ranges
  3. Geolocation Services: Map IP ranges to geographic locations
  4. Network Analysis: Compare and sort IP addresses efficiently

Error Handling Best Practices

When working with IP address conversions, always consider error handling:


import ipaddress

def safe_ip_conversion(ip_address):
    try:
        ip_obj = ipaddress.ip_address(ip_address)
        return int(ip_obj)
    except ValueError as e:
        print(f"Invalid IP address: {ip_address}")
        print(f"Error: {e}")
        return None

# Test with valid and invalid IPs
valid_ip = "192.168.1.1"
invalid_ip = "999.999.999.999"

result1 = safe_ip_conversion(valid_ip)
result2 = safe_ip_conversion(invalid_ip)

print(f"Valid IP result: {result1}")
print(f"Invalid IP result: {result2}")

Valid IP result: 3232235777
Invalid IP address: 999.999.999.999
Error: '999.999.999.999' does not appear to be an IPv4 or IPv6 address
Invalid IP result: None

Performance Comparison

Different methods have varying performance characteristics:

  • ipaddress module: Most readable, good for general use
  • Manual conversion: Fastest for IPv4-only applications
  • socket module: Good balance of performance and readability

For most applications, the ipaddress module provides the best combination of reliability and maintainability.

Conclusion

Converting IP addresses to integers in Python is straightforward with multiple available methods. For most use cases, the built-in ipaddress module offers the cleanest and most reliable approach. Manual conversion provides deeper understanding and better performance for IPv4-only scenarios. The socket module serves as a good middle ground.

Choose the method that best fits your needs:

  • Use ipaddress for general applications requiring IPv4 and IPv6 support
  • Use manual conversion for high-performance IPv4-only applications
  • Use socket when working with network-level operations

Always implement proper error handling to manage invalid IP addresses gracefully. With these techniques, you can efficiently work with IP addresses in your Python applications.