Home >>c programs >C Program to find class of an IP Address

C Program to find class of an IP Address

C Program to find class of an IP Address

In this example, we will see a C program through which we can find the class of a given IP address.

An IPv4 has range between 0 to 255 and IP Addresses are divided into 5 classes

Class A		  1 	to 	126
Class B		128 	to 	191
Class C		192	to 	223
Class D		224	to	239
Class E		240	to 	254
Program:

#include <stdio.h>
#include <string.h>
/*
Function : extractIpAddress
Arguments : 
1) sourceString - String pointer that contains ip address
2) ipAddress - Target variable short type array pointer that will store ip address octets
*/
void extractIpAddress(unsigned char *sourceString,short *ipAddress)
{
unsigned short len=0;
unsigned char  oct[4]={0},cnt=0,cnt1=0,i,buf[5];

len=strlen(sourceString);
for(i=0;i<len;i++)
{
if(sourceString[i]!='.'){
buf[cnt++] =sourceString[i];
}
if(sourceString[i]=='.' || i==len-1){
buf[cnt]='\0';
cnt=0;
oct[cnt1++]=atoi(buf);
}
}
ipAddress[0]=oct[0];
ipAddress[1]=oct[1];
ipAddress[2]=oct[2];
ipAddress[3]=oct[3];
}
int main()
{
unsigned char ip[20]={0};
short ipAddress[4];
printf("Enter IP Address (xxx.xxx.xxx.xxx format): ");
scanf("%s",ip);
extractIpAddress(ip,&ipAddress[0]);
printf("\nIp Address: %03d. %03d. %03d. %03d\n",ipAddress[0],ipAddress[1],ipAddress[2],ipAddress[3]);
if(ipAddress[0]>=0 && ipAddress[0]<=127)
printf("Class A Ip Address.\n");
if(ipAddress[0]>127 && ipAddress[0]<191)
printf("Class B Ip Address.\n");
if(ipAddress[0]>191 && ipAddress[0]<224)
printf("Class C Ip Address.\n");
if(ipAddress[0]>224 && ipAddress[0]<=239)
printf("Class D Ip Address.\n");
if(ipAddress[0]>239)
printf("Class E Ip Address.\n");
return 0;
}

Output:
Enter IP Address (xxx.xxx.xxx.xxx format): 192.127.763.273
Ip Address: 192. 127. 251. 017
Class C Ip Address.