I'm preparing for a quiz, and I have a strong suspicion I may be tasked with implementing such a function. Basically, given an IP address in network notation, how can we get that from a 32 bit integer into a string in it's dotted decimal notation (something like 155.247.182.83)...? Obviously we can't be using any type of inet functions either...I'm stumped!
Let's making it clearer. The integer representation of the IP address: 192.168. 1.34 <==> (((192 * 256 + 168) * 256 + 1) * 256 + 34.
IP addresses are whole numbers (the definition of integer, although they often do not meet the integer definition of some programming languages). There is one who strongly disagrees (see the comments @ stackoverflow.com/q/45067655/3745413).
An IP address is a string of numbers separated by periods. IP addresses are expressed as a set of four numbers — an example address might be 192.158. 1.38. Each number in the set can range from 0 to 255.
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.
You actually can use an inet function. Observe.
main.c:
#include <arpa/inet.h> main() { uint32_t ip = 2110443574; struct in_addr ip_addr; ip_addr.s_addr = ip; printf("The IP address is %s\n", inet_ntoa(ip_addr)); }
The results of gcc main.c -ansi; ./a.out
is
The IP address is 54.208.202.125
Note that a commenter said this does not work on Windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With