Given a valid IPv4 address in the form of string and it follows Class Full addressing. The task is to determine class of given IPv4 address as well as separate Network and Host ID part from it.
Examples:
Input : 1.4.5.5 Output : Given IP address belongs to Class A Network ID is 1 Host ID is 4.5.5 Input : 130.45.151.154 Output : Given IP address belongs to Class B Network ID is 130.45 Host ID is 151.154
Approach
- For determining the class: The idea is to check first octet of IP address. As we know, for class A first octet will range from 1 – 126, for class B first octet will range from 128 – 191, for class C first octet will range from 192- 223, for class D first octet will range from 224 – 239, for class E first octet will range from 240 – 255.
- For determining the Network and Host ID: We know that Subnet Mask for Class A is 8, for Class B is 16 and for Class C is 24 whereas Class D and E is not divided into Network and Host ID.
For 2nd Example, first octet is 130. So, it belongs to Class B. Class B has subnet mask of 16. So, first 16 bit or first two octet is Network ID part and rest is Host ID part.
Hence, Network ID is 130.45 and Host ID is 151.154
// C program to determine class, Network // and Host ID of an IPv4 address #include<stdio.h> #include<string.h> // Function to find out the Class char findClass( char str[]) { // storing first octet in arr[] variable char arr[4]; int i = 0; while (str[i] != '.' ) { arr[i] = str[i]; i++; } i--; // converting str[] variable into number for // comparison int ip = 0, j = 1; while (i >= 0) { ip = ip + (str[i] - '0' ) * j; j = j * 10; i--; } // Class A if (ip >=1 && ip <= 126) return 'A' ; // Class B else if (ip >= 128 && ip <= 191) return 'B' ; // Class C else if (ip >= 192 && ip <= 223) return 'C' ; // Class D else if (ip >= 224 && ip <= 239) return 'D' ; // Class E else return 'E' ; } // Function to separate Network ID as well as // Host ID and print them void separate( char str[], char ipClass) { // Initializing network and host array to NULL char network[12], host[12]; for ( int k = 0; k < 12; k++) network[k] = host[k] = ' |