C Program to convert IP address to 32-bit longint

Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
union iptolint
{
    char ip[16];
    long  n;
};
 
long  conv(char []);
 
main()
{
    union iptolint ipl;
    printf(" Read the IP Address to be converted\n");
    scanf("%s",ipl.ip);
    ipl.n=conv(ipl.ip);
    printf(" Equivalent 32-bit long int is : %lu \n",ipl.n);
}
 
long conv(char ipadr[])
{
    long num=0,val;
    int p=24;
    char *tok,*ptr;
    tok=strtok(ipadr,".");
    while( tok != NULL)
    {
        val=strtol(tok,&ptr,10);
        num+=  val * (long)pow(2,p);
        p=p-8;
        tok=strtok(NULL,".");
    }
    return(num);
}
Ansten Lobo

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in