By Danny Kalev, ITworld |  How-to

The Dotted Decimal Notation
An IP address is a 32-bit unsigned integer. It's usually written as
four numbers separated by dots, as in: 212.227.196.186. This format is
knows as the "dotted decimal notation". Applications use struct in_addr
to store the binary representation of an IP address. Struct in_addr is
declared in the header as follows:

struct
{
union
{
struct
{
unsigned char s_b1, s_b2, s_b3, s_b4;
} S_un_b;
struct
{
unsigned short s_w1, s_w2;
} S_un_w;
} S_un;

The struct contains a union that wraps three different views of the
same data variable: as four octets, as two unsigned short integers, or
as a single unsigned long integer.

in_ddr to String Conversion
To obtain a string representation of an in_addr object, use the
inet_ntoa() function that has the following prototype:

#include
#include

This function takes an in_addr object as an argument and returns a
pointer to a static string containing its dotted decimal form. You
should copy the result to a private buffer because each call to
inet_ntoa() will assign a new value to the string.

The deprecated function inet_addr() performs the reverse, namely
converting a dotted decimal string to its binary representation.

This function returns the unsigned long representation of the dotted
decimal string cp. There are two problems with this function, though.
First, it returns unsigned long rather than an in_addr object. This
forces programmers to use ugly casts. The second problem is that you
have no way to distinguish between a return value of -1 (indicating an
error) or the address 255.255.255.255 since both these values have an
identical binary representation. You may still find occurrences of
inet_addr() in legacy code. However, in new applications you should use

This function converts the string cp to an in_addr object and writes
the result to paddr. Note that unlike most library functions, inet_aton
() returns 0 to indicate an error, and a nonzero value to indicate
success. Next week I will show how to translate an IP address to a
hostname and vice versa.