IP 数据报头解析器:分析和转换 IP 地址
该程序旨在分析 IP 数据报头并提取其源地址和目的地址,并将结果以点分十进制格式显示。它接收输入的二进制形式的 IP 数据报头,该报头必须为 20 字节(160 位)。然后,程序使用 substring 方法从输入的 IP 数据报头中提取源地址和目的地址的二进制形式。接下来,使用 binaryToDecimal 方法将二进制地址转换为点分十进制表示。最后,程序输出转换后的源地址和目的地址。
import java.util.Scanner;
public class IPHeaderAnalyzer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter IP header in binary form (20 bytes): ");
String ipHeader = scanner.nextLine();
if (ipHeader.length() != 160) {
System.out.println("Invalid IP header length. Expected 160 bits (20 bytes). ");
return;
}
String sourceAddress = ipHeader.substring(96, 128);
String destinationAddress = ipHeader.substring(128, 160);
String sourceAddressDecimal = binaryToDecimal(sourceAddress);
String destinationAddressDecimal = binaryToDecimal(destinationAddress);
System.out.println("Source Address (in decimal): ' + sourceAddressDecimal);
System.out.println("Destination Address (in decimal): ' + destinationAddressDecimal);
}
private static String binaryToDecimal(String binary) {
StringBuilder decimal = new StringBuilder();
for (int i = 0; i < binary.length(); i += 8) {
String octet = binary.substring(i, i + 8);
int decimalValue = Integer.parseInt(octet, 2);
decimal.append(decimalValue);
if (i < binary.length() - 8) {
decimal.append(".");
}
}
return decimal.toString();
}
}
该程序演示了如何从二进制 IP 数据报头中提取和解析源地址和目的地址。它为理解 IP 数据报头的结构以及如何使用 Java 代码解析它提供了一个基本的框架。
原文地址: https://www.cveoy.top/t/topic/fn3n 著作权归作者所有。请勿转载和采集!