how to obtain the ip address of the connected wifi router in android programmatically?

后端 未结 2 1211
旧巷少年郎
旧巷少年郎 2021-02-03 14:36

I want to obtain the ip address of the the wifi router to which my android phone is connected? I know that we can get the mac/BSSId and SSID by using the android APIS but I don\

相关标签:
2条回答
  • 2021-02-03 15:00

    Since formatIpAddress is Deprecatted, here is the alternative :

    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"
    }
    
    0 讨论(0)
  • 2021-02-03 15:04

    What you want is DhcpInfo....

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

    This will determine the formatted gateway IP address, which should be what you're looking for.

    0 讨论(0)
提交回复
热议问题