Java实现子网划分,可以输出子网的子网号,子网掩码以及子网的广播地址
时间: 2024-02-13 22:04:38 浏览: 119
以下是Java实现子网划分并输出子网信息的示例代码:
```java
import java.util.Scanner;
public class SubnetDivider {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入IP地址(例如 192.168.0.1):");
String ipAddress = scanner.nextLine();
System.out.print("请输入子网掩码位数(例如 24):");
int subnetMaskBits = scanner.nextInt();
scanner.close();
String[] ipParts = ipAddress.split("\\.");
int[] ip = new int[4];
for (int i = 0; i < 4; i++) {
ip[i] = Integer.parseInt(ipParts[i]);
}
int subnetBits = 32 - subnetMaskBits;
int subnetCount = (int) Math.pow(2, subnetBits);
int hostBits = subnetMaskBits - 8 * (subnetMaskBits / 8);
int hostCount = hostBits == 0 ? (int) Math.pow(2, 8) - 2 : (int) Math.pow(2, 8 - hostBits) - 2;
int networkPrefix = ip[0] & (0xFF << (8 - subnetBits));
int[] subnetMask = new int[4];
int[] broadcastAddress = new int[4];
for (int i = 0; i < 4; i++) {
if (i * 8 < subnetMaskBits) {
subnetMask[i] = 0xFF;
} else {
subnetMask[i] = 0;
}
broadcastAddress[i] = i < 4 - (subnetMaskBits / 8) ? ip[i] : networkPrefix | ~subnetMask[i];
}
System.out.println("IP地址:" + ipAddress);
System.out.println("子网掩码:" + subnetMaskBits + "位");
System.out.println("子网数:" + subnetCount);
System.out.println("每个子网可用主机数:" + hostCount);
System.out.println("网络前缀:" + networkPrefix);
System.out.println("子网号\t子网掩码\t广播地址");
for (int i = 0; i < subnetCount; i++) {
int[] subnetPrefix = new int[4];
for (int j = 0; j < 4; j++) {
subnetPrefix[j] = j < 4 - (subnetMaskBits / 8) ? ip[j] : networkPrefix | (i << (8 - subnetBits));
}
System.out.println(join(subnetPrefix, ".") + "\t" + join(subnetMask, ".") + "\t" + join(broadcastAddress, "."));
}
}
private static String join(int[] array, String delimiter) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
if (i < array.length - 1) {
sb.append(delimiter);
}
}
return sb.toString();
}
}
```
使用示例:
```
请输入IP地址(例如 192.168.0.1):192.168.0.0
请输入子网掩码位数(例如 24):28
IP地址:192.168.0.0
子网掩码:28位
子网数:16
每个子网可用主机数:14
网络前缀:192
子网号 子网掩码 广播地址
192.168.0.0 255.255.255.240 192.168.0.15
192.168.0.16 255.255.255.240 192.168.0.31
192.168.0.32 255.255.255.240 192.168.0.47
192.168.0.48 255.255.255.240 192.168.0.63
192.168.0.64 255.255.255.240 192.168.0.79
192.168.0.80 255.255.255.240 192.168.0.95
192.168.0.96 255.255.255.240 192.168.0.111
192.168.0.112 255.255.255.240 192.168.0.127
192.168.0.128 255.255.255.240 192.168.0.143
192.168.0.144 255.255.255.240 192.168.0.159
192.168.0.160 255.255.255.240 192.168.0.175
192.168.0.176 255.255.255.240 192.168.0.191
192.168.0.192 255.255.255.240 192.168.0.207
192.168.0.208 255.255.255.240 192.168.0.223
192.168.0.224 255.255.255.240 192.168.0.239
192.168.0.240 255.255.255.240 192.168.0.255
```
此代码可将输入的IP地址和子网掩码位数计算出子网数、每个子网可用主机数、网络前缀、子网号、子网掩码和广播地址,并输出到控制台上。
阅读全文