2012-01-27 372 views
3

如何從代碼中找到路由器的IP地址(網關地址)?如何從android中的代碼中知道路由器的ip地址?

WifiInfo.getIpAddress() - 返回設備的IP地址。

在shell命令中「ipconfig」不返回任何值。

這裏是我的解決方案,但請讓我知道是否有更好的方法來做到這一點:

WifiManager manager = (WifiManager)getSystemService(WIFI_SERVICE); 
DhcpInfo info = manager.getDhcpInfo(); 
info.gateway; 
+0

可能重複[如何在Android中獲取網關和子網掩碼的詳細信息?編程方式](http://stackoverflow.com/questions/5387036/how-to-get-gateway-and-subnet-mask-details-in-android-programmatically) – slayton 2012-01-27 17:06:19

+3

'ipconfig'是一個Windows命令。 linux命令是帶if的'ifconfig'。Android似乎並沒有使用'netcfg' – slayton 2012-01-27 17:07:38

+0

當然,我的意思是'ifconfig'。 'netcfg'返回ip的設備:( – HotIceCream 2012-01-29 15:19:19

回答

11

嘿,這可能會幫助您:DHCPInfo

final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE); 
final DhcpInfo dhcp = manager.getDhcpInfo(); 
final String address = Formatter.formatIpAddress(dhcp.gateway); 

添加以下行AndroidManifest .xml以訪問wifi功能:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

由於formatIpAdd RESS現在已被棄用,你可以使用下面的代碼

byte[] myIPAddress = BigInteger.valueOf(manager.getIpAddress()).toByteArray(); 
ArrayUtils.reverse(myIPAddress); 
InetAddress myInetIP = InetAddress.getByAddress(myIPAddress); 
String myIP = myInetIP.getHostAddress(); 
+0

如果我給了靜態IP和禁用的DHCP,那麼我得到0.0.0.0(dhcp.serverAddress)。 – ravz 2014-12-08 06:14:54

+0

Formatter.formatIpAddress()[已被棄用](https:/ /developer.android.com/reference/android/text/format/Formatter.html#formatIpAddress(int))。 – 2017-06-01 02:48:39

-2

要獲取IP地址,嘗試getInetAddress();

-1

試試這個:

$ busybox ip route show 

它在我的平板電腦終端仿真器工作正常!

+0

busybox僅適用於rooted Android – Lizz 2014-12-13 09:17:26

0

我覺得你這樣做的方式是最好的(據我所知),這裏是從科爾多瓦插件,做同樣的方式一些示例代碼:的

public class GetRouterIPAddress extends CordovaPlugin { 

    @Override 
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { 
     try { 
      String ip = getRouterIPAddress(); 
      if (ip.equals("0.0.0.0")) { 
       callbackContext.error("No valid IP address"); 
       return false; 
      } 
      callbackContext.success(ip); 
      return true; 
     } catch(Exception e) { 
      callbackContext.error("Error while retrieving the IP address. " + e.getMessage()); 
      return false; 
     } 
    } 

    private String formatIP(int ip) { 
     return String.format(
      "%d.%d.%d.%d", 
      (ip & 0xff), 
      (ip >> 8 & 0xff), 
      (ip >> 16 & 0xff), 
      (ip >> 24 & 0xff) 
     ); 
    } 

    private String getRouterIPAddress() { 
     WifiManager wifiManager = (WifiManager) cordova.getActivity().getSystemService(Context.WIFI_SERVICE); 
     DhcpInfo dhcp = wifiManager.getDhcpInfo(); 
     int ip = dhcp.gateway; 
     return formatIP(ip); 
    } 
} 

https://github.com/vallieres/cordova-plugin-get-router-ip-address/blob/master/src/android/GetRouterIPAddress.java

相關問題