Saturday, December 4, 2010

in_addr to string(char*)

The other day I needed to turn a IPv4 address to a string in C. I figured some others would find it useful:

char* hexToCharIP(struct in_addr addrIP)
char* ip;
unsigned int intIP;
memcpy(&intIP, &addrIP,sizeof(unsigned int));
int a = (intIP >> 24) & 0xFF;
int b = (intIP >> 16) & 0xFF;
int c = (intIP >> 8) & 0xFF;
int d = intIP & 0xFF;
if((ip = (char*)malloc(16*sizeof(char))) == NULL)
return NULL;
sprintf(ip, "%d.%d.%d.%d", d,c,b,a);
return ip;


  1. The routine you're looking for is inet_ntoa(), part of the c standard library.

    The routine inet_ntoa() takes an Internet address and returns an ASCII
    string representing the address in `.' notation. The routine
    inet_makeaddr() takes an Internet network number and a local network
    address and constructs an Internet address from it. The routines
    inet_netof() and inet_lnaof() break apart Internet host addresses,
    returning the network number and local network address part, respec-

    It's in arpa/inet.h, man inet_ntoa should be able to tell you more.