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

再次提问如何用java获得子网掩码?
大家好!

如何用java获得子网掩码?包括linux和windows下的,有什么类可用?
最好给出些代码,谢谢!!
上一次提问过这个问题了,终于有一位朋友给出了详细代码,我也将分值全给了他,但今天发现不对,得出的   结果错误。所以不得不再次提问了。
那位朋友的代码如下:
import   java.net.*;
import   java.util.*;
public   class   SubNetMask   {
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();
}
}
}

--------------------------

address   =   192.168.99.176     //IP地址  
subnet   =   192.168.99               //子网掩码
address   =   192.168.98.176     //IP地址  
subnet   =   192.168.98               //子网掩码
address   =   192.168.0.218       //IP地址  
subnet   =   192.168.0               //子网掩码
而我的真实的子网掩码是:192.168.0.255

谢谢大家的参与!!



------解决方案--------------------
//在得到ia后用下面的方法可以得到掩码
long mask = 0;
for (int n = 0; n < ia.getNetworkPrefixLength(); n++) {
mask |= 1 < < (31 - n);
}
System.out.println( "mask = "
+ ((mask > > 24) & 0xff) + ". "
+ ((mask > > 16) & 0xff) + ". "
+ ((mask > > 8) & 0xff) + ". "
+ (mask & 0xff));