Free cookie consent management tool by TermsFeed The inet_aton() function in Python | Pythontic.com

The inet_aton() function in Python

Function Name:

inet_aton(ip_address)

Parameter(s):

The ip_address, which needs to be converted from the dotted-quad, string format to 32 bit packed binary format.

Function Overview:

As per Internet Protocol version 4(IPv4), an IP Address is a 32-bit number. These IPv4 addresses are represented as four decimal numbers. 

For example, issuing a ping to www.example.com returns a string 
64 bytes from 23.62.12.104: icmp_seq=0 ttl=58 time=4.202 ms
Here, the IP address returned is 23.62.12.104 which is in IPv4 format. 
In the similar way the IP address
127.0.0.1 which refers to the localhost is also in IPv4 format.

In IPv4, the four decimal numbers are separated by a dot and each number ranges from 0 to 255. This format is called the dotted-quad string format.

The Python function inet_aton() from the socket module, converts an IPv4 address from the dotted-quad string format to 32-bit packed binary format. The binary format returned could be passed to any program that requires IP address as an object of C type struct in_addr.

Note: An IP address is an address that uniquely identifies a computer system in a network that is connected using TCP/IP protocol. When a hostname like www.example.com is typed in a web browser the request goes to a nearby nameserver that translates the domain name to the actual IP – which can be either in IPv4 format or in IPv6 format. 

Example:

# Example Python program that converts an IPv4
# address from dotted-quad string format to binary
# format
import socket
import struct

# IP address Dotted-quad format
ipv4Address       = "192.168.0.0"

# Convert to binary format
ip32bitBinary    = socket.inet_aton(ipv4Address) 

print("IP address in binary format:")
print(ip32bitBinary)
print(type(ip32bitBinary))

print("Number of bytes in the IP address:")
print(len(ip32bitBinary))

Output:

IP address in binary format:
b'\xc0\xa8\x00\x00'
<class 'bytes'>
Number of bytes in the IP address:
4

 


Copyright 2025 © pythontic.com