Wednesday, October 5, 2011

ntohl function c

 * ntohl linux 
 * ntohl socket
 * network to host long long
 * network to host byte order

#include <netinet/in.h>

unsigned long ntohl(unsigned long netlong);

Return value
The ntohl function returns the value supplied in the netlong parameter with the byte order reversed. If netlong is already in host byte order, then this function will reverse it. It is up to the application to determine if the byte order must be reversed. 

The ntohl function takes a 32-bit number in TCP/IP network byte order (the AF_INET or AF_INET6 address family) and returns a 32-bit number in host byte order.
The ntohl function can be used to convert an IPv4 address in network byte order to the IPv4 address in host byte order.
This function does not do any checking to determine if the netlong parameter is a valid IPv4 address.

How to Implement 
Initializing an IN_ADDRANY AF_INET Address  
The steps used above are as follows:
  1. The value adr_inet is defined using the structure sockaddr_in (line 1).
  2. The address adr_inet is zeroed by calling memset(3) in line 4. (This is optional.)  
  3. The address family is established by assigning the value AF_INET to adr_inet.sin_family (line 6)  
  4. A wild port number is specified in line 7. Notice the use of the function ntohs(3). The value zero indicates a wild port number.  
  5. A wild IP number is assigned in line 8. Again, note the use of the ntohl(3) function to perform the endian conversion.  
  6. The size of the address is simply computed as the size of the structure adr_inet (line 9).
Another commonly used IP number is This refers to the loopback device. The loopback device lets you communicate with another process on the same host as your process. You'll see more of this IP number later. For now, just note how the address can be assigned below. Line 8 could be changed to the following statement:

adr_inet.sin_addr.s_addr = ntohl(INADDR_LOOPBACK); 

This will address your current host through the loopback device. In the next section, you will learn how to set up any IP number and port number. 

See Also
  1. htonl
  2. htons
  3. ntohs

1 comment: