In this program, we will read an IP address from the user and print the class of input IP address.
Program/Source Code:
The source code to print the class of the given IP address is given below. The given program is compiled and executed successfully.
// Java program to print the class
// of a given IP address
import java.util.Scanner;
public class Main {
static void printIpClass(String sourceString) {
short len = 0;
int oct[] = new int[4];
String buf = "";
short cnt = 0;
short i = 0;
len = (short) sourceString.length();
for (i = 0; i < len; i++) {
if (sourceString.charAt(i) != '.') {
buf += sourceString.charAt(i);
}
if (sourceString.charAt(i) == '.' || i == len - 1) {
oct[cnt++] = Integer.parseInt(buf);
buf = "";
}
}
System.out.println("Octete1 : " + oct[0]);
System.out.println("Octete2 : " + oct[1]);
System.out.println("Octete3 : " + oct[2]);
System.out.println("Octete4 : " + oct[3]);
if (oct[0] >= 0 && oct[0] <= 127)
System.out.printf("Class A Ip Address.\n");
else if (oct[0] > 127 && oct[0] < 191)
System.out.printf("Class B Ip Address.\n");
else if (oct[0] > 191 && oct[0] < 224)
System.out.printf("Class C Ip Address.\n");
else if (oct[0] > 224 && oct[0] <= 239)
System.out.printf("Class D Ip Address.\n");
else if (oct[0] > 239)
System.out.printf("Class E Ip Address.\n");
}
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);
String ip;
int i = 0;
System.out.print("Enter valid IP address: ");
ip = SC.next();
printIpClass(ip);
}
}
Output:
Enter valid IP address: 192.168.10.235
Octete1 : 192
Octete2 : 168
Octete3 : 10
Octete4 : 235
Class C Ip Address.
Explanation:
In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contain two static methods printIpClass() and main().
The printIpClass() method is used to extract octets from the input IP address and print the class of IP address.
The main() method is an entry point for the program. Here, we read an IP address in string format. Then we used printIpClass() method and printed the class of input IP address.
In this program, we will read an IP address from the user and print the class of input IP address.
Program/Source Code:
The source code to print the class of the given IP address is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contain two static methods printIpClass() and main().
The printIpClass() method is used to extract octets from the input IP address and print the class of IP address.
The main() method is an entry point for the program. Here, we read an IP address in string format. Then we used printIpClass() method and printed the class of input IP address.