TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
昨天写代码写到一半,突然想到,之前测试的时候都是手动输入子网掩码的,因而想着如何自动获得子网掩码,于是就Google了下,发现确实是有这方面的东西,可能我是自己比较笨,看不懂别人的代码,也因为找到的代码很少注释(这可能是中国人写程序的习惯),所以我就不想再看了,但是多少还是有点启发的,查看了jdk以后,知道可以通过NetworkInterface、InterfaceAddress这两个类来实现,可以获得子网掩码前缀,然后通过运算就能得到子网掩码,要说明的是,我计算掩码的方法很土但是很好用,代码也很容易看的懂,还有一个要说明的是,我是xp系统,没有安装ipv6协议. 代码:
public class SubnetMask {
/**
* @param args
*/
public static String getSubnetMask(){
int prefix=0;
int[] ipSplit=new int[4];
String subnetMask=null;
InetAddress localMachine=null;
try {
localMachine=InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NetworkInterface netCard=null;
try {
netCard=NetworkInterface.getByInetAddress(localMachine);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<InterfaceAddress> localInterface=null;
localInterface=netCard.getInterfaceAddresses();
Iterator<InterfaceAddress> iterator=null;
iterator=localInterface.iterator();
while(iterator.hasNext()){
InterfaceAddress temp=null;
temp=iterator.next();
prefix=temp.getNetworkPrefixLength();
}
int index=0;
int split=0;
int remainder=0;
split=prefix/8;
remainder=prefix%8;
while(index<split){
ipSplit[index]=255;
index++;
}
if(remainder==1)
ipSplit[index]=128;
if(remainder==2)
ipSplit[index]=192;
if(remainder==3)
ipSplit[index]=224;
if(remainder==4)
ipSplit[index]=240;
if(remainder==5)
ipSplit[index]=248;
if(remainder==6)
ipSplit[index]=252;
if(remainder==7)
ipSplit[index]=254;
index++;
while(index<remainder){
ipSplit[index]=0;
index++;
}
subnetMask=String.valueOf(ipSplit[0])+"."+String.valueOf(ipSplit[1])+"."+String.valueOf(ipSplit[2])+"."+String.valueOf(ipSplit[3]);
return subnetMask;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String subnetMask=getSubnetMask();
System.out.println(subnetMask);
}
}
源码下载:http://file.javaxxz.com/2014/11/7/000440656.zip |
|