Determining the class of an IP address is a common task in networking. IP addresses are categorized into five classes: A, B, C, D, and E. The class of an IP address is determined by the value of the first octet (the first 8 bits) in the address.
Here's a C program that determines the class of an IP address provided by the user. We'll take an IP address as input and then analyze the first octet to determine the class. Let's break it down step by step:
#include <stdio.h>
#include <string.h>
int main() {
char ip_address[16]; // An IPv4 address can have at most 15 characters
printf("Enter an IP address: ");
scanf("%s", ip_address);
// Split the IP address into octets
int octet1, octet2, octet3, octet4;
sscanf(ip_address, "%d.%d.%d.%d", &octet1, &octet2, &octet3, &octet4);
// Determine the class based on the first octet
char ip_class;
if (octet1 >= 1 && octet1 <= 126) {
ip_class = 'A';
} else if (octet1 >= 128 && octet1 <= 191) {
ip_class = 'B';
} else if (octet1 >= 192 && octet1 <= 223) {
ip_class = 'C';
} else if (octet1 >= 224 && octet1 <= 239) {
ip_class = 'D';
} else if (octet1 >= 240 && octet1 <= 255) {
ip_class = 'E';
} else {
printf("Invalid IP address.\n");
return 1; // Exit the program with an error code
}
printf("The IP address %s belongs to Class %c.\n", ip_address, ip_class);
return 0;
}
Explanation of the code:
We include the necessary header files for input/output and string manipulation.
We declare an array
ip_address
to store the user input. IPv4 addresses can have at most 15 characters.We prompt the user to enter an IP address and use
scanf
to read the input into theip_address
array.We then use
sscanf
to split the IP address into four octets (integers).Based on the value of the first octet, we determine the class of the IP address and store it in the variable
ip_class
.The code checks which class the IP address belongs to using a series of if-else statements.
If the first octet falls outside the valid range for all classes, it's considered an invalid IP address, and an error message is displayed. The program then exits with an error code (1).
Finally, the program prints the determined IP address class to the console.
Here's an example of how this program works:
Enter an IP address: 192.168.1.1
The IP address 192.168.1.1 belongs to Class C.
In this example, the IP address "192.168.1.1" is recognized as a Class C address.