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