java获取子网掩码
时间: 2023-08-10 18:05:40 浏览: 121
可以使用Java中的InetAddress和NetworkInterface类来获取子网掩码。
以下是一个示例代码:
```
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class SubnetMaskExample {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();
while (interfaceList.hasMoreElements()) {
NetworkInterface iface = interfaceList.nextElement();
Enumeration<InetAddress> addrList = iface.getInetAddresses();
while (addrList.hasMoreElements()) {
InetAddress address = addrList.nextElement();
if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof java.net.Inet4Address) {
System.out.println("IP地址:" + address.getHostAddress());
System.out.println("子网掩码:" + getSubnetMask(iface));
}
}
}
}
public static String getSubnetMask(NetworkInterface iface) throws SocketException {
Enumeration<InetAddress> addrList = iface.getInetAddresses();
while (addrList.hasMoreElements()) {
InetAddress address = addrList.nextElement();
if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof java.net.Inet4Address) {
short prefixLength = iface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
int mask = 0xffffffff << (32 - prefixLength);
byte[] bytes = new byte[] {(byte) (mask >>> 24), (byte) (mask >> 16 & 0xff), (byte) (mask >> 8 & 0xff), (byte) (mask & 0xff)};
try {
return InetAddress.getByAddress(bytes).getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
}
```
该代码会遍历所有的网络接口,获取每个接口的IP地址和子网掩码。需要注意的是,获取子网掩码需要根据网络前缀长度进行计算,这里使用了Java中的位运算来实现。
阅读全文