Java,擷取子網路遮罩__java

來源:互聯網
上載者:User

    昨天寫代碼寫到一半,突然想到,之前測試的時候都是手動輸入子網路遮罩的,因而想著如何自動獲得子網路遮罩,於是就google了下,發現確實是有這方面的東西,可能我是自己比較笨,看不懂別人的代碼,也因為找到的代碼很少注釋(這可能是中國人寫程式的習慣),所以我就不想再看了,但是多少還是有點啟發的,查看了jdk以後,知道可以通過NetworkInterface、InterfaceAddress這兩個類來實現,可以獲得子網路遮罩首碼,然後通過運算就能得到子網路遮罩,要說明的是,我計算掩碼的方法很土但是很好用,代碼也很容易看的懂,還有一個要說明的是,我是xp系統,沒有安裝ipv6協議,因為安裝了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); } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.