Is it worth mentionning that there is also inet_aton ?
You can find the man page here, below is a short description and a short synopsis.
This solution will work on most POSIX systems, but I'm sure there is some equivalent in the Windows APIs, and even some abstraction wrapper.
inet_ntoa() is specified in POSIX.1-2001. inet_aton() is not specified in POSIX.1-2001, but is available on most systems.
Linux Programmer's Manual
inet_aton() converts the Internet host address cp from the IPv4 numbers-and-dots notation into binary form (in network byte order) and stores it in the structure that inp points to.
SYNOPSIS
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton(const char *cp, struct in_addr *inp);
char *inet_ntoa(struct in_addr in);
EXAMPLE
An example of the use of inet_aton() and inet_ntoa() is shown below. Here are some example runs:
$ ./a.out 226.000.000.037 # Last byte is in octal
226.0.0.31
$ ./a.out 0x7f.1 # First byte is in hex
127.0.0.1
Program source
#define _BSD_SOURCE
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
struct in_addr addr;
if (argc != 2) {
fprintf(stderr, "%s <dotted-address>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (inet_aton(argv[1], &addr) == 0) {
fprintf(stderr, "Invalid address\n");
exit(EXIT_FAILURE);
}
printf("%s\n", inet_ntoa(addr));
exit(EXIT_SUCCESS);
}
Further informations
Byte ordering (@Jonathan Leffler)
The inet_ntoa() function converts the Internet host address in
, given in network byte order, to a string in IPv4 dotted-decimal notation.
inet_aton()
converts the Internet host address cp
from the IPv4 numbers-and-dots notation into binary form (in network byte order) and stores it in the structure that inp
points to.
Structure of in_addr
(@POW)
The structure in_addr as used in inet_ntoa(), inet_makeaddr(), inet_lnaof() and inet_netof() is defined in as:
typedef uint32_t in_addr_t;
struct in_addr {
in_addr_t s_addr;
};
Compare to address independently of computer-endianness
Addresses in in_addr
are in network byte order (big-endian), so as pointed by @glglgl, you have to use ntohl
, whose man page is available here.
The ntohl()
function converts the unsigned integer netlong
from network byte order to host byte order.
uint32_t ntohl(uint32_t netlong);