Last modified: Sep 13, 2026

Convert String to IP Address in Python

Convert String to IP Address in Python

In many applications, you may need to convert a string representation of an IP address into its numeric form or vice versa. This process is especially useful when working with networking tasks, logging systems, or database storage optimizations.

In this article, we’ll explore several ways to handle such conversions in Python. We’ll cover both converting a string to an integer (numeric IP) and back again.

Understanding IP Addresses

An Internet Protocol (IP) address is a unique identifier assigned to each device connected to a network. IPv4 addresses consist of four octets separated by dots, like 192.168.1.1. Each octet ranges from 0 to 255.

Sometimes, it's helpful to represent these addresses as integers for easier manipulation or comparison. Converting between formats can be done easily in Python using built-in modules.

Method 1: Using socket.inet_aton

One common way to convert a string IP address into bytes is using the socket module’s inet_aton() function.


import socket

# Convert string IP to packed bytes
ip_string = "192.168.1.1"
packed_ip = socket.inet_aton(ip_string)

print("Packed Bytes:", packed_ip)

Packed Bytes: b'\xc0\xa8\x01\x01'

This method converts the dotted decimal format into a 4-byte binary representation, which can then be used for further processing.

Converting Packed Bytes to Integer

To get the numeric value of the IP address, you can unpack those bytes using the struct module.


import struct

# Unpack bytes into integer
ip_int = struct.unpack("!I", packed_ip)[0]
print("Integer IP:", ip_int)

Integer IP: 3232235777

Here, !I tells struct.unpack to interpret the data as a big-endian unsigned integer.

Method 2: Manual Conversion Using Bit Shifting

If you prefer not to rely on external libraries, you can perform the conversion manually using bit shifting operations.


def ip_to_int(ip):
    # Split the string into parts and shift bits accordingly
    parts = ip.split('.')
    result = 0
    for part in parts:
        result = (result << 8) + int(part)
    return result

ip_string = "192.168.1.1"
numeric_ip = ip_to_int(ip_string)
print("Numeric IP:", numeric_ip)

Numeric IP: 3232235777

This approach splits the IP string into its components and shifts each part appropriately before combining them into a single integer.

Reverse Conversion: From Integer Back to String

You might also want to convert an integer back to its string representation. Here’s how to do it:


def int_to_ip(num):
    # Convert integer back to dotted decimal format
    return '.'.join(str((num >> shift) & 0xFF) for shift in [24, 16, 8, 0])

numeric_ip = 3232235777
ip_string = int_to_ip(numeric_ip)
print("String IP:", ip_string)

String IP: 192.168.1.1

The reverse operation involves bit masking and shifting to extract each octet from the full integer.

Using ipaddress Module for Robust Handling

Python provides a powerful standard library called ipaddress for handling IP addresses more safely and accurately.


import ipaddress

# Parse string to IP object
ip_obj = ipaddress.ip_address("192.168.1.1")
print("IP Object:", ip_obj)
print("Integer Value:", int(ip_obj))

IP Object: 192.168.1.1
Integer Value: 3232235777

This method handles validation automatically and supports both IPv4 and IPv6 addresses seamlessly.

Why Convert IP Addresses?

There are several reasons why developers might need to convert IP addresses:

  • Storing IPs efficiently in databases
  • Comparing ranges of IP addresses
  • Implementing firewalls or access control lists
  • Logging and analytics where numeric representations are preferred

By converting IPs to integers, comparisons become simple arithmetic operations instead of complex string parsing.

Error Handling Best Practices

When dealing with user input or external sources, always validate the IP address before conversion.


try:
    ip_obj = ipaddress.ip_address("invalid_ip")
except ValueError as e:
    print("Invalid IP Address:", e)

Invalid IP Address: 'invalid_ip' does not appear to be an IPv4 or IPv6 address

Using exception handling ensures your program doesn’t crash unexpectedly due to malformed inputs.

Conclusion

Converting between string and numeric forms of IP addresses is a fundamental skill in network programming. Whether you choose manual methods or built-in tools like socket, struct, or ipaddress, understanding these techniques will help you build robust applications.

Remember to consider edge cases, validate inputs, and select the right tool depending on your use case.