Taken from the original at http://www.ecst.csuchico.edu/~beej/guide/net/ ... see end of writeup for Copyright statement.

IP Addresses and How to Deal With Them

Fortunately for you, there are a bunch of functions that allow you to manipulate IP addresses. No need to figure them out by hand and stuff them in a long with the << operator.

First, let's say you have a struct sockaddr_in ina, and you have an IP address "132.241.5.10" that you want to store into it. The function you want to use, inet_addr(), converts an IP address in numbers-and-dots notation into an unsigned long. The assignment can be made as follows:

ina.sin_addr.s_addr = inet_addr("132.241.5.10");

Notice that inet_addr() returns the address in Network Byte Order already -- you don't have to call htonl(). Swell!

Now, the above code snippet isn't very robust because there is no error checking. See, inet_addr() returns -1 on error. Remember binary numbers? (unsigned) -1 just happens to correspond to the IP address 255.255.255.255! That's the broadcast address! Wrongo. Remember to do your error checking properly.

All right, now you can convert string IP addresses to longs. What about the other way around? What if you have a struct in_addr and you want to print it in numbers-and-dots notation? In this case, you'll want to use the function inet_ntoa() ("ntoa" means "network to ascii") like this:

printf("%s", inet_ntoa(ina.sin_addr));

That will print the IP address. Note that inet_ntoa() takes a struct in_addr as an argument, not a long. Also notice that it returns a pointer to a char. This points to a statically stored char array within inet_ntoa() so that each time you call inet_ntoa() it will overwrite the last IP address you asked for. For example:

char *a1, *a2;
 :
 :
a1 = inet_ntoa(ina1.sin_addr);  /* this is 198.92.129.1 */
a2 = inet_ntoa(ina2.sin_addr);  /* this is 132.241.5.10 */
printf("address 1: %s\n",a1);
printf("address 2: %s\n",a2);

will print:

address 1: 132.241.5.10
address 2: 132.241.5.10

If you need to save the address, strcpy() it to your own character array.

That's all on this topic for now. Later, you'll learn to convert a string like "whitehouse.gov" into its corresponding IP address (see DNS, below.)


Prev | Up | Next


Copyright © 1995, 1996 by Brian "Beej" Hall. This guide may be reprinted in any medium provided that its content is not altered, it is presented in its entirety, and this copyright notice remains intact. Contact beej@ecst.csuchico.edu for more information.

Log in or register to write something here or to contact authors.