using inet_addr
The first
function that you will learn about is an older function, which should probably
no longer be used in new code. However, you will find it in a lot of existing
network code, and so you should become familiar with it and know its
limitations. The synopsis for inet_addr(3) is as follows:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned
long inet_addr(const char *string);
This function
accepts an input C string argument string and parses the dotted-quad notation
into a 32-bit Internet address value. The 32-bit value returned is in network
byte order. If the input argument string does not represent a valid dotted-quad
address, the value INADDR_NONE is returned. Any other returned value represents
the converted value.
NOTE
The 32-bit value
returned by inet_addr(3) is in network byte order. Do not use htonl(3) on the
returned value, because it is already in network byte order.
CAUTION
The inet_addr(3)
does not establish a reason code in errno when
INADDR_NONE is
returned. So, do not test errno or report it when an error indication is
returned by this function. The program shown below is an example of
how you would use this function. To compile and run the program, perform the
following:
gcc -c
-D_GNU_SOURCE -Wall inetaddr.c
gcc
inetaddr.o -o inetaddr
./inetaddr
The program below when it is run, converts a C string constant containing an IP
number into a network
sequenced 32-bit IP address. This value is then placed into an AF_INET socket
address
and bound to the
socket.
Example
thanks for providing the sample code.
ReplyDelete