Here's a simple method to do it: The (ip >> 8)
, (ip >> 16)
and (ip >> 24)
moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF
isolates the least significant byte at each step.
void print_ip(unsigned int ip)
{
unsigned char bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);
}
There is an implied bytes[0] = (ip >> 0) & 0xFF;
at the first step.
Use snprintf()
to print it to a string.