请用Java计算子网掩码
时间: 2024-05-27 12:06:36 浏览: 193
计算子网掩码的工具
Java可以通过NetworkInterface、InterfaceAddress这两个类来实现获取子网掩码前缀的功能,然后通过运算就能得到子网掩码[^1]。下面是一个获取子网掩码的例子:
```java
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
public class SubnetMaskCalculator {
public static void main(String[] args) throws Exception {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue;
}
List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : interfaceAddresses) {
InetAddress inetAddress = interfaceAddress.getAddress();
if (!(inetAddress instanceof java.net.Inet4Address)) {
continue;
}
short prefixLength = interfaceAddress.getNetworkPrefixLength();
int mask = 0xffffffff << (32 - prefixLength);
byte[] bytes = new byte[]{(byte) (mask >>> 24), (byte) (mask >> 16 & 0xff), (byte) (mask >> 8 & 0xff), (byte) (mask & 0xff)};
InetAddress netmask = InetAddress.getByAddress(bytes);
System.out.println("Interface name : " + networkInterface.getDisplayName());
System.out.println("IP address : " + inetAddress.getHostAddress());
System.out.println("Subnet mask : " + netmask.getHostAddress());
}
}
}
}
```
阅读全文