user2597333
user2597333

Reputation: 41

Can I get the IP address of the access point to I am connected to over wifi?

Hi I am new to android programming. I am basically trying to connect to an access point and send it come commands. After connecting to it over wifi, is it possible to programatically obtain it's IP address so that I can establish a http connection with it? So far I know that we can obtain the device IP, but not sure if the access point IP can be obtained. Please help. Thanks in advance.

Upvotes: 4

Views: 8365

Answers (3)

yiteng lin
yiteng lin

Reputation: 31

public static String getApIpAddr(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
    byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress);
    try {
        String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress();
        return apIpAddr;
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return null;
}

private static byte[] convert2Bytes(int hostAddress) {
    byte[] addressBytes = { (byte)(0xff & hostAddress),
            (byte)(0xff & (hostAddress >> 8)),
            (byte)(0xff & (hostAddress >> 16)),
            (byte)(0xff & (hostAddress >> 24)) };
    return addressBytes;
}

Upvotes: 3

user2545733
user2545733

Reputation:

I am using this to get the IP address

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();
                        if (!inetAddress.isLoopbackAddress())
                         { 
                         //My IP address
                               String Ip= inetAddress.getHostAddress().toString();

                         }   
                       }
                  }

            }
     catch (SocketException e) 
     { 
       Log.e("Error occurred  ", e.toString());
      }

Upvotes: 0

mti2935
mti2935

Reputation: 12037

I assume you mean the outside (public) IP address of the access point that the device is connected to. If so, yes there is a simple way to get the public IP address of the access point that a device is connected to. Simply setup a script on a web server that will echo back the IP address of any client that connects to it (similar to www.whatismyip.com). Then, your device just needs to do a GET request to the script, and this will return the outside IP of the access point that the device is connected to.

Upvotes: 0

Related Questions