Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to IP Address - C

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!

like image 620
Kris Richards Avatar asked Nov 05 '09 12:11

Kris Richards


People also ask

How do I convert my number to an IP address?

Let's making it clearer. The integer representation of the IP address: 192.168. 1.34 <==> (((192 * 256 + 168) * 256 + 1) * 256 + 34.

Is IP address integer or string?

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).

Is IP address a string?

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.


2 Answers

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.

like image 43
Wernsey Avatar answered Sep 21 '22 23:09

Wernsey


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.

like image 120
Rose Perrone Avatar answered Sep 20 '22 23:09

Rose Perrone