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 "188.8.131.52" 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("184.108.40.206");
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:
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 220.127.116.11 */
a2 = inet_ntoa(ina2.sin_addr); /* this is 18.104.22.168 */
printf("address 1: %s\n",a1);
printf("address 2: %s\n",a2);
address 1: 22.214.171.124
address 2: 126.96.36.199
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 email@example.com for more information.