2014-08-27 40 views

回答

5

這裏有一個方法將獲得掩碼,也就是網絡前綴的長度。最小的API是9,並且需要INTERNET許可。該地址有一個'/'前綴,但可以通過添加.toString.substring(1)等來輕鬆刪除。

public void logLocalIpAddresses() { 
    Enumeration<NetworkInterface> nwis; 
    try { 
     nwis = NetworkInterface.getNetworkInterfaces(); 
     while (nwis.hasMoreElements()) { 

      NetworkInterface ni = nwis.nextElement(); 
      for (InterfaceAddress ia : ni.getInterfaceAddresses()) 

       Log.i(TAG, String.format("%s: %s/%d", 
         ni.getDisplayName(), ia.getAddress(), ia.getNetworkPrefixLength())); 
     } 

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

我需要API 8,但我想這會做。乾杯! – RumburaK 2014-09-02 10:17:58

+0

> API 9沒問題,因爲以太網開始在API 11中使用! – RumburaK 2014-09-02 10:27:28