Write the code in half yesterday, suddenly thought, before the test is manually input subnet mask, so think how to automatically get the subnet mask, so on Google, found that there is really something, maybe I am more stupid, can not understand other people's Code, Also because the code found rarely commented (this may be the Chinese writing Program habit), so I do not want to see, but how much is still a little bit of inspiration, after looking at the JDK, know that you can through the NetworkInterface, interfaceaddress these two classes to implement, The subnet mask prefix can be obtained, and then the subnet mask can be obtained by operation. To illustrate, I calculate the Mask method is very good, but very good, the code is also easy to read, there is one to explain that I am an XP system, did not install the IPv6 protocol, because the installation of IPv6 will have multiple results
Code:
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.pri Ntstacktrace (); } 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); } }