Wednesday, September 7, 2011

using inet_ntoa linux


using inet_ntoa
There are times when a socket address represents the address of a user that has connected to your server, or represents the sender of a UDP packet. The job of converting a network sequenced 32-bit
value into dottedquad notation is inconvenient. Hence, the inet_ntoa(3) function has been provided. The synopsis of the function is as follows:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

char *inet_ntoa(struct in_addr addr);

The function requires only one input argument addr. Note that the struct in_addr is an internal part of the Internet socket address. The address is converted into a static buffer, which is internal to the function. This character array pointer is returned as the return value. The results will be valid only until the next call to this function.

Review the sockaddr_in structure in previous blog (), "Domains and Address Families," . This will help you visualize the physical address structure that you are working with. If a socket address addr exists in your program as a sockaddr_in structure, then the following code shows how to use inet_ntoa(3) to perform the conversion. The IP number is converted to a string and reported, using the printf(3) function:

struct sockaddr_in addr; /* Socket Address */
printf("IP ADDR: %s\n", inet_ntoa(addr.sin_addr));

A complete example program is provided below. To compile and run this program, the following steps are required:

gcc -c -D_GNU_SOURCE -Wall inetntoa.c
gcc inetntoa.o -o inetntoa
./inetntoa

The program below uses the same steps to set up the address as did the previous example program. The function inet_ntoa(3) is called upon to allow the IP number to be displayed.

Example

No comments:

Post a Comment