Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

PROGRAM: 5

Aim:-
Write a program to implement and find class, network ID and host ID from given
IPV4 address.

Theory:-
IPV4 address is a 32 bit IP address which can be divided into five sub-classes. These
are:
 Class A
 Class B
 Class C
 Class D
 Class E

Each of these classes has a valid range of IP addresses. Classes D and E are reserved
for multicast and experimental purposes respectively. The order of bits in the first octet
determine the classes of IP address.

IPv4 address is divided into two parts:


 Network ID
 Host ID

The class of IP address is used to determine the bits used for network ID and host ID
and the number of total networks and hosts possible in that particular class. Each ISP or
network administrator assigns IP address to each device that is connected to its
network.
Code:-
#include<iostream>
#include<string>

using namespace std;

char findClass(string S){


int octet = 0;
int i = 0;
while (S[i] != '.'){
octet = octet*10 + int(S[i]) - 48;
i++;
}

if (octet >=1 && octet <= 126)


return 'A';
else if (octet >= 128 && octet <= 191)
return 'B';
else if (octet >= 192 && octet <= 223)
return 'C';
else if (octet >= 224 && octet <= 239)
return 'D';
else
return 'E';
}

void separate(string S, char ipClass){


string networkId,hostId;
int i = 0,dotCount = 0;

if (ipClass == 'A'){
while (S[i] != '.')
networkId.push_back(S[i++]);
i++;
while (S[i] != '\0')
hostId.push_back(S[i++]);
cout<<"Network ID is "<<networkId;
cout<<"\nHost ID is "<<hostId;
}
else if (ipClass == 'B'){
while (dotCount < 2){
networkId.push_back(S[i++]);
if (S[i] == '.')
dotCount++;
}
i++;
while (S[i] != '\0')
hostId.push_back(S[i++]);

cout<<"Network ID is "<<networkId;
cout<<"\nHost ID is "<<hostId;
}
else if (ipClass == 'C'){
while (dotCount < 3){
networkId.push_back(S[i++]);
if (S[i] == '.')
dotCount++;
}
i++;
while (S[i] != '\0')
hostId.push_back(S[i++]);

cout<<"Network ID is "<<networkId;
cout<<"\nHost ID is "<<hostId;
}
else
cout<<"In this Class, IP address is not divided into Network and Host ID";
}

int main()
{
string S;
cout<<"Enter IPV4 Address : ";
cin>>S;
char ipClass = findClass(S);
cout<<"Given IP address belongs to Class "<<ipClass<<"\n";
separate(S, ipClass);
return 0;
}

Output:-
Discussion:-
We have learnt how to fetch class, network ID and host ID from an IPV4 address.
It is also that for class D and E address, IPV4 address can not be split into network
and host ID.

You might also like