Wednesday, September 7, 2011

inet_network in linux

using inet_network
There might be occasions in which it is more convenient to have the dottedquad IP number converted into a 32-bit host-ordered value. This is more convenient when you are applying mask values to extract host or network bits from the addresses. The function synopsis for inet_network(3) is as follows:

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

unsigned long inet_network(const char *addr);

This function takes one input string containing a dotted quad address in argument addr. The return value is the 32-bit value of the IP address, but in host-order format. However, if the input value is malformed, the returned result will be 0xFFFFFFFF (all 1 bits). Having the returned value in host-endian order means that you can safely assume constants for mask values and bit positions. If the returned value were in network-endian order, the constants and code would then be different for different CPU platforms.

An example of how inet_network(3) might be used is shown next. The following shows how to extract the network address from a class C address:

unsigned long net_addr;
net_addr = inet_network("") & 0xFFFFFF00;

The value assigned to net_addr would be the value 0xC0A80900 (or in dottedquad notation). The logical and operation masked out the low-order eight bits to arrive at the network ID without the host ID.


No comments:

Post a Comment