输入IP地址和掩码,用Java语言实现判断IP种类,输出网络地址和输出校验码
时间: 2023-06-19 07:03:12 浏览: 93
以下是Java代码实现:
```java
import java.util.Scanner;
public class IPClassification {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入IP地址和掩码
System.out.print("请输入IP地址:");
String[] ipAddress = scanner.nextLine().split("\\.");
System.out.print("请输入掩码:");
String[] mask = scanner.nextLine().split("\\.");
// 将IP地址和掩码转换成二进制字符串
String ipBinary = toBinaryString(ipAddress);
String maskBinary = toBinaryString(mask);
// 判断IP地址种类并输出网络地址和校验码
if (ipAddress[0].equals("127")) {
System.out.println("该IP地址为本地回环地址");
System.out.println("网络地址:" + ipAddress[0] + ".0.0.0");
System.out.println("校验码:" + "0.0.0.0");
} else if (ipAddress[0].matches("[01]{8}") && ipAddress[1].matches("[01]{8}")
&& ipAddress[2].matches("[01]{8}") && ipAddress[3].matches("[01]{8}")
&& mask[0].matches("[01]{8}") && mask[1].matches("[01]{8}")
&& mask[2].matches("[01]{8}") && mask[3].matches("[01]{8}")) {
int firstOctet = Integer.parseInt(ipAddress[0]);
if (firstOctet >= 1 && firstOctet <= 126) {
System.out.println("该IP地址为A类地址");
System.out.println("网络地址:" + firstOctet + ".0.0.0");
System.out.println("校验码:" + mask[0] + "." + mask[1] + "." + mask[2] + "." + mask[3]);
} else if (firstOctet >= 128 && firstOctet <= 191) {
System.out.println("该IP地址为B类地址");
System.out.println("网络地址:" + ipAddress[0] + "." + ipAddress[1] + ".0.0");
System.out.println("校验码:" + mask[0] + "." + mask[1] + "." + mask[2] + "." + mask[3]);
} else if (firstOctet >= 192 && firstOctet <= 223) {
System.out.println("该IP地址为C类地址");
System.out.println("网络地址:" + ipAddress[0] + "." + ipAddress[1] + "." + ipAddress[2] + ".0");
System.out.println("校验码:" + mask[0] + "." + mask[1] + "." + mask[2] + "." + mask[3]);
} else if (firstOctet >= 224 && firstOctet <= 239) {
System.out.println("该IP地址为D类地址");
System.out.println("网络地址:" + ipAddress[0] + "." + ipAddress[1] + "." + ipAddress[2] + "." + ipAddress[3]);
System.out.println("校验码:" + "不能用于网络地址");
} else if (firstOctet >= 240 && firstOctet <= 255) {
System.out.println("该IP地址为E类地址");
System.out.println("网络地址:" + ipAddress[0] + "." + ipAddress[1] + "." + ipAddress[2] + "." + ipAddress[3]);
System.out.println("校验码:" + "不能用于网络地址");
} else {
System.out.println("无效IP地址");
}
} else {
System.out.println("无效IP地址或掩码");
}
}
// 将IP地址和掩码转换成二进制字符串
private static String toBinaryString(String[] ipAddress) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
sb.append(String.format("%8s", Integer.toBinaryString(Integer.parseInt(ipAddress[i]))).replace(' ', '0'));
}
return sb.toString();
}
}
```
使用示例:
```
请输入IP地址:192.168.0.1
请输入掩码:255.255.255.0
该IP地址为C类地址
网络地址:192.168.0.0
校验码:255.255.255.0
```
阅读全文