inet_addr inet_aton inet_ntoa Functions

 < Day Day Up > 



inet_addr/ inet_aton/ inet_ntoa Functions

These miscellaneous conversion functions provide the ability to convert IP address from string form (dotted-notation) to binary network format (and vice versa). All of these functions are prefixed with inet, which refers to the fact that they operate on Internet addresses (IPv4).

#include <netinet/in.h> #include <arpa/inet.h> unsigned long inet_addr( const char *addr ); char *inet_ntoa( struct in_addr in ); int inet_aton( const char *addr, struct in_addr *inp );

The most common of the address conversion functions is inet_addr. This function takes an IP address string in dotted-notation (“<N>.<N>.<N>.<N>”) and converts it into a binary format address (unsigned int) in network byte order. The inet_ntoa function takes an in_addr structure (contained within the sockaddr_in structure) and returns a character pointer of a string in dotted-IP notation. Finally, the inet_aton function provides conversion of a dotted-notation IP string into binary format address in network byte order. This function differs in format from the inet_addr in that a return value is available for error checking. Let’s now look at examples of each of these functions (see Listing 3.10).

Listing 3.10 Examples of the socket address functions.

start example
/* inet_addr() example */ unsigned int addr; const char *straddr = "192.168.1.1"; addr = inet_addr( straddr ); /* inet_ntoa() example */ char *str; struct sockaddr_in sa1; sa1.sin_addr.s_addr = inet_addr( "192.168.1.2" ); str = inet_ntoa( sa1.sin_addr ); printf( "%s\n", str ); /* inet_aton example */ char str[30]; int ret; struct sockaddr_in sa; strcpy( str, "192.168.1.3" ); ret = inet_aton( str, &sa.sin_addr ); printf( "%08x\n", sa.sin_addr.s_addr );
end example



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net