IP Address Conversion

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: 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; unsigned long S_addr; } S_un; } in_addr; 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 char * inet_ntoa(struct in_addr addr); 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. String to in_addr Conversion The deprecated function inet_addr() performs the reverse, namely converting a dotted decimal string to its binary representation. inet_addr() has the following prototype: unsigned long inet_addr(const char *cp); 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 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 inet_aton() instead: int inet_aton(const char *cp, struct in_addr *paddr); 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.
Free Course: JavaScript: The Good Parts
View Comments
You Might Like
Join the discussion
Be the first to comment on this article. Our Commenting Policies