Wednesday, April 24, 2013

Convert IP to Integer

Formula would be :-

First Octet * (256 ^ 3) + Second Octet * (256 ^ 2) 
+ Third Octet * (256 ^ 1) + Fourth Octet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdio.h"
#include "math.h"

/* Function to convert IP address into Integer
 * Input  : IP address array
 * Output : Converted IP
 */
unsigned int ip_to_int(unsigned in[])
{
        return ((in[0]*(pow(256,3))) + (in[1]*(pow(256,2))) +
                        (in[2]*(pow(256,1))) + (in[3]));
}

int main(int argc, char **argv)
{

        unsigned ip_addr[] = { 192, 168, 1, 124 };
        printf("Input  : %d.%d.%d.%d\n", ip_addr[0], ip_addr[1],
                                        ip_addr[2], ip_addr[3]);
        printf("Output : %u\n", ip_to_int(ip_addr));

        return 0;
}

[root@Imperfecto_1 ~] gcc run.c && ./a.out
Input  : 192.168.1.124
Output : 3232235900

No comments:

Post a Comment