C Program to convert IP address to 32-bit long int

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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
union iptolint
{
    char ip[16];
    unsigned long int n;
};
unsigned long int conv(char []);
 
main()
{
    union iptolint ipl;
    printf(" Read the IP Address tobe converted\n");
    scanf("%s",ipl.ip);
    ipl.n=conv(ipl.ip);
    printf(" Equivalent 32-bit long int is : %lu\n",ipl.n);
}
 
unsigned long int conv(char ipadr[])
{
    unsigned long int num=0,val;
    char *tok,*ptr;
    tok=strtok(ipadr,".");
    while( tok != NULL)
    {
        val=strtoul(tok,&ptr,0);
        num=(num << 8) + val;
        tok=strtok(NULL,".");
    }
    return(num);
}

One Response to “C Program to convert IP address to 32-bit long int”

Leave a Reply