如何从代码中找到路由器(网关地址)的IP地址?
WifiInfo.getIpAddress()
- 返回设备的IP地址。
在Shell命令"ipconfig"中不返回任何值。
这是我的解决方案,请告诉我是否有更好的方法:
WifiManager manager = (WifiManager)getSystemService(WIFI_SERVICE);
DhcpInfo info = manager.getDhcpInfo();
info.gateway;
如何从代码中找到路由器(网关地址)的IP地址?
WifiInfo.getIpAddress()
- 返回设备的IP地址。
在Shell命令"ipconfig"中不返回任何值。
这是我的解决方案,请告诉我是否有更好的方法:
WifiManager manager = (WifiManager)getSystemService(WIFI_SERVICE);
DhcpInfo info = manager.getDhcpInfo();
info.gateway;
嗨,这可能会对你有所帮助:DHCPInfo
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);
为了访问WiFi功能,请将以下行添加到AndroidManifest.xml中:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
由于 formatIpAddress 已被弃用,现在您可以使用以下代码
byte[] myIPAddress = BigInteger.valueOf(manager.getIpAddress()).toByteArray();
ArrayUtils.reverse(myIPAddress);
InetAddress myInetIP = InetAddress.getByAddress(myIPAddress);
String myIP = myInetIP.getHostAddress();
我认为你现在的做法是最好的(据我所知),以下是一个 Cordova 插件的示例代码,它也是用同样的方式实现:
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);
}
}
试试这个:
$ busybox ip route show
在我的平板电脑上使用终端模拟器可以正常运行!
要获取IP地址,请尝试使用getInetAddress();
ifconfig
。netcfg
返回设备的IP地址:( - HotIceCream