inet_pton - Convert an IP address in string format to packed binary format using Python

The inet_pton() function in the socket module of Python converts an IP address in string format to packed binary format. The Python examples convert an IPv4 address and an IPv6 address from string format to packed binary format.

socket Updated 24 Jun 2019 1 min read

Overview

  • The Python function inet_pton() from the socket module converts an IP address in string format to a packed binary format.

Example – Converting an IPv4 address into binary format

python
# Example Python Program to convert an IPv4 IP address

# into packed binary format

import socket

ipAddress   = "127.0.0.1";

binaryIP    = socket.inet_pton(socket.AF_INET, ipAddress);

print("IP address in string format:%s"%ipAddress);

print("Packed binary format of the IP address: %s"%(binaryIP));

Output

Output
IP address in string format:127.0.0.1

Packed binary format of the IP address: b'\x7f\x00\x00\x01'

Example – Converting an IPv6 address into binary format

python
# Example Python Program to convert an IPv6 IP address

# into packed binary format

import socket

ipv6Address         = "0:0:0:0:0:ffff:7f00:1";

ipv6AddressBinary   = socket.inet_pton(socket.AF_INET6, ipv6Address);

print("An IPv6 address in string format:%s"%ipv6Address);

print("Packed binary format of the given IP6 address: %s"%(ipv6AddressBinary));

Output

Output
An IPv6 address in string format:0:0:0:0:0:ffff:7f00:1

Packed binary format of the given IP6 address: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x7f\x00\x00\x01'