我想获取我的Android手机所连接的wifi路由器的IP地址?我知道我们可以通过使用android APIS获取mac / BSSId和SSID,但我找不到找到找到它的IP地址的方法吗?
我发现获取手机IP地址的代码拥有wifi路由器
WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
int ipAddress = myWifiInfo.getIpAddress();
System.out.println("WiFi address is " + android.text.format.Formatter.formatIpAddress(ipAddress))
但未能得到我想要的东西
你想要的是DhcpInfo
....
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);
这将确定格式化的网关IP地址,这应该是您正在寻找的。
由于formatIpAddress是Deprecatted,以下是替代方法:
public String getHotspotAdress(){
final WifiManager manager = (WifiManager)super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
int ipAddress = dhcp.gateway;
ipAddress = (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) ?
Integer.reverseBytes(ipAddress) : ipAddress;
byte[] ipAddressByte = BigInteger.valueOf(ipAddress).toByteArray();
try {
InetAddress myAddr = InetAddress.getByAddress(ipAddressByte);
return myAddr.getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("Wifi Class", "Error getting Hotspot IP address ", e);
}
return "null"
}