Friday, November 25, 2016

C Program to find given IP Address belongs to which Class(A,B,C,D,E)


#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int check_digit_dot(char ipstr[])
{
 for(int i=0;i<strlen(ipstr);i++)
 {
  if((ipstr[i]>=48 && ipstr[i]<=57)||(ipstr[i]=='.'))
  {
   //i++;
  }
  else
     return 0;   }
  }
   return 1;
}

int check_ip(char ipstr[])
{
 char temp[20];
 int a,num,dot=0,j=0,numcount=0;
 a=check_digit_dot(ipstr);
 temp[0]='\0';
 if(a==0)
  return 0;
  else
   {
    for(int i=0;i<=strlen(ipstr);i++)
    {
      if(ipstr[i]!='.')
       {
             temp[j]=ipstr[i];
             j++;
             temp[j]='\0';
       }
      else
       {
             num=atoi(temp);
            // cout<<"num="<<num<<"\n";
             dot++;
             if((num>=0 && num<=255) && strlen(temp)>0)
             {  numcount++; }
             //cout<<"numcount="<<numcount<<"\n";
             j=0;
             temp[j]='\0';
       }
    }
    // after last dot
    num=atoi(temp);
   // cout<<"num="<<num<<"\n";
    if ((num>=0 && num<=255) && strlen(temp)>0)
    { numcount++; }
   // cout<<"numcount="<<numcount<<"\n";
  }

  //cout<<"dots="<<dot<<"  numcount="<<numcount<<"\n";
  if(dot==3 && numcount==4)
    return 1;
  else
    return 0;
 }

 

void main()
{
 clrscr();
 char a[50],temp[50];
 int check,j=0,num;
 cout<<" enter ip address\n";
 cin>>a;
 check=check_ip(a);
 if(check==0)
 {
  cout<<"not valid ip address\n";
  }
  else
  {
   cout<<" valid  ip address\n";
   temp[0]='\0';
   for(int i=0;i<strlen(a);i++)
   {
    if(a[i]=='.')
     {     break;       }
    else
     {
      temp[j]=a[i];
      j++;
      temp[j]='\0';
     }
   }

    num=atoi(temp);
    cout<<"num:"<<num<<"\n";

    if((num>=0)&&(num<128))
    cout<<"given ip address is class A\n";
    else if((num>=128)&&(num<192))
    cout<<"given ip address is class B";
    else if((num>=192)&&(num<224))
    cout<<"given ip address is class C";
    else if((num>=224)&&(num<240))
    cout<<"given ip address is class D";
    else
    cout<<"given ip address is class E";
  }

  getch();
 }

No comments:

Post a Comment