Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wifi.getDhcpInfo() in Android returns the wrong IP gateway

Tags:

android

wifi

dhcp

I am writing an Android application that needs to connect to different Wifi networks based on the user's selection. I need to retrieve the gateway IP address from the networkInfo. The Problem I am facing is that if I am connected to wifi network configuration A, and then want to switch to network configuration B, the wifi.getDhcpInfo(); returns to gateway IP address of network A. After several tries through the User interface workflow, it eventually returns the gateway IP of network B. Code snipet is below. Any ideas how to determine when the newly enabled network will return accurate Dhcp information so that I can get it reliably. Is there an ansynchronous event that I can catch for example, etc. Thanks.

WifiConfiguration config = wifiConfiguredNetworks.get(SSID);
enableNetworkResult = false;
enableNetworkResult = wifi.enableNetwork(config.networkId,true);
if (enableNetworkResult == true) {
    this.networkInfo = wifi.getDhcpInfo(); // does not return proper IP info    
    this.DeviceIP = android.text.format.Formatter.formatIpAddress(networkInfo.gateway);
}
like image 372
user1157108 Avatar asked Nov 14 '22 11:11

user1157108


1 Answers

I have exactly same issue and able to fix it with workaround. Just need to create worker thread with checking wifiManager.getConnectionInfo().getIpAddress() == 0 Something like this:

final Handler h = new Handler();
final WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
new Thread(new Runnable() {
    @Override
    public void run() {
        while (wifiManager.getConnectionInfo().getIpAddress() == 0) {
            Log.d(TAG, "waiting for valid ip");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        h.post(new Runnable() {
            @Override
            public void run() {
                // proceed here
            }
        });
    }
}).start();

I also tried all possible listeners, receivers etc. Nothing helped. The only way to get valid dhcp info is to wait for not null ip address.

like image 187
deviant Avatar answered Nov 16 '22 02:11

deviant