Print IP address in dotted-decimal format without converting to string in C
Few binary operations can be used to print a binary IP address in human-readable dotted-decimal format without using inet_ntoa() function that requires a string buffer. The following example shows how to do it.
[neo@techpulp ~]# cat pip.c
#include <stdio.h>
#define IP_QUAD(ip) (ip)>>24,((ip)&0x00ff0000)>>16,((ip)&0x0000ff00)>>8,((ip)&0x000000ff)
int main(int argc, char *argv[])
{
unsigned long my_ip = 0xa0653b20;
printf("My IP Address (0x%x) is %d.%d.%d.%d\n", my_ip, IP_QUAD(my_ip));
return 0;
}
[neo@techpulp ~]#
In the above program the macro IP_QUAD uses right-shift operator to extract each byte of the integer from MSB to LSB to expand it in to four arguments. This macro can be used pretty easily with “%u.%u.%u.%u” as format specifier for printf(). This method of printing IP address is faster as string conversion is done using inet_ntoa() library function.
Let us run the above C program
[neo@techpulp ~]# gcc pip.c -o pip [neo@techpulp ~]# ./pip My IP Address (0xa0653b20) is 160.101.59.32 [neo@techpulp ~]#
Same method can be used to convert IP address to a string using sprintf instead of printf.


about 1 year ago
Nice article, how does this work on a 64bit system or on a Little Endian machine..say an ARM box. The beauty of using inet_pton/inet_aton and so forth is they take into account these issues.
about 3 months ago
Endianness issue (reverse order on my x86 Linux box), btw., which the library function wouldn’t have. An #ifdef and reversing the macro when needed might help.