2016-11-23 36 views
3

我遇到了幾個關於以編程方式在Android上獲取IPv4和IPv6地址的討論。這些其他的問題和答案的問題是:使用未過時的方法以編程方式獲取IPv4和IPv6,無論是在Wifi還是在Cari​​er網絡上時

  • 這些問題/答案相當老的現在因此經常棄用。我正在尋找一種方法來完成未棄用的方式(例如,InetAddressUtils已棄用,其他人也是如此)。
  • 我想知道如何獲得在IPv4或IPv6地址當在無線上或在運營商的網絡上。

有沒有人誰可以告訴我如何讓它在整齊方式完成,無需冗長的方法(如果可能的話)?

+0

https://developer.android.com/reference/android/net/ConnectivityManager.html –

+0

謝謝,我之前已經檢查了它,但該頁面當時並不是很有幫助 – lehrer

回答

1

對於IPv4,IPV6可以使用

public String getIpv4() { 
      try { 
       for (Enumeration<NetworkInterface> en = NetworkInterface 
         .getNetworkInterfaces(); en.hasMoreElements();) { 
        NetworkInterface intf = en.nextElement(); 
        for (Enumeration<InetAddress> enumIpAddr = intf 
          .getInetAddresses(); enumIpAddr.hasMoreElements();) { 
         InetAddress inetAddress = enumIpAddr.nextElement(); 
         System.out.println("ip1--:" + inetAddress); 
         System.out.println("ip2--:" + inetAddress.getHostAddress()); 

         if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { 
          String ipaddress = inetAddress.getHostAddress().toString(); 
          return ipaddress; 
         } 


        } 
       } 
      } catch (Exception ex) { 
       Log.e("IP Address", ex.toString()); 
      } 
      return null; 
     } 

//ipv6 
    public String getLocalIpV6() { 
     try { 
      for (Enumeration<NetworkInterface> en = NetworkInterface 
        .getNetworkInterfaces(); en.hasMoreElements();) { 
       NetworkInterface intf = en.nextElement(); 
       for (Enumeration<InetAddress> enumIpAddr = intf 
         .getInetAddresses(); enumIpAddr.hasMoreElements();) { 
        InetAddress inetAddress = enumIpAddr.nextElement(); 
        System.out.println("ip1--:" + inetAddress); 
        System.out.println("ip2--:" + inetAddress.getHostAddress()); 

        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) { 
         String ipaddress = inetAddress.getHostAddress().toString(); 
         return ipaddress; 
        } 


       } 
      } 
     } catch (Exception ex) { 
      Log.e("IP Address", ex.toString()); 
     } 
     return null; 
    } 
相關問題