inet_pton is a function in the C programming language that converts an IPv4 or IPv6 address from text format to binary format. The name inet_pton stands for “Internet presentation to network” and is part of the standard networking library on Unix-like operating systems.
The syntax of the inet_pton function is as follows:
#include <arpa/inet.h>
int inet_pton(int af, const char *src, void *dst);
af
: An integer specifying the address family. This can be either AF_INET for IPv4 or AF_INET6 for IPv6.src
: A pointer to a string containing the IP address in text format.dst
: A pointer to a buffer where the converted binary IP address will be stored.
The return value of inet_pton is 1 if the conversion was successful, 0 if src does not contain a valid IP address, or -1 if an error occurred.
Here’s an example usage of the inet_pton function:
#include <stdio.h>
#include <arpa/inet.h>
int main() {
const char* ip_address = "192.168.1.1";
struct in_addr ipv4_addr;
int result = inet_pton(AF_INET, ip_address, &ipv4_addr);
if (result == 1) {
printf("Binary representation: %u\n", ipv4_addr.s_addr);
} else if (result == 0) {
printf("Invalid IP address.\n");
} else {
perror("Error converting IP address.");
}
return 0;
}
In this example, we convert the IPv4 address “192.168.1.1” from text format to binary format using the inet_pton function with AF_INET as the address family parameter. The resulting binary representation is printed to stdout.