Home » C programs » Advance C programs

C program to find class of an IP Address

Each computer which is connected to the network has an identifier to recognise connected computer address, known as IP (Internet Protocol) Address.

An IPv4 has 4 octets having decimal value between 0 to 255 and depending on the first octet’s value, IP Addresses divided into 5 classes: (Read more: IP Address and Its 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

In this program, we will read an IP Address and find its class.

Program to find class of an IP Address in C



#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): 145.160.017.001

Ip Address: 145. 160. 017. 001
Class B Ip Address.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.