日期:2014-05-20  浏览次数:20771 次

如何用java获得子网掩码?
大家好!

如何用java获得子网掩码?包括linux和windows下的,有什么类可用?
最好给出些代码,谢谢!!

------解决方案--------------------
20?? 现在的知识,越来越不值钱了

public static void main(String[] args) {
try {
Enumeration <NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while (eni.hasMoreElements()) {
NetworkInterface ni = eni.nextElement();
List <InterfaceAddress> lia = ni.getInterfaceAddresses();
Iterator <InterfaceAddress> iia = lia.iterator();
while (iia.hasNext()) {
InterfaceAddress ia = iia.next();
InetAddress a = ia.getAddress();
if (!a.isLoopbackAddress()) {
String ha = a.getHostAddress();
System.out.println( "address = " + ha);
short ml = (short) (ia.getNetworkPrefixLength() / 8);
String[] as = ha.split( "\\. ");
String ns = " ";
for (int i = 0; i < ml; i++) {
ns += as[i];
if (i < ml - 1) {
ns += ". ";
}
}
System.out.println( "subnet = " + ns);
}
}

}
} catch (Exception e) {
e.printStackTrace();
}

}