androidandroid-wifihotspot

Not able to ping device which started the LocalOnlyHotSpot when mobile data is on


I am using wifiManager.startLocalOnlyHotspot to start a hotspot with no internet access so that the connecting device can send files to this device using sockets. Everything is working as expected but I am not able to ping the connected wifi hotspot device when the mobile data of the same device which is pinging is on. When I disable the mobile data I am able to ping to the server IP I get from the utility class I am posting that utility method. Can anyone explain to me the concept I am missing?

 public static String getHotspotIpAddress(Context context) {
    WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);

    DhcpInfo dhcpInfo = wifimanager == null ? null : wifimanager.getDhcpInfo();
    if (dhcpInfo != null) {
        int address = dhcpInfo.serverAddress;
        return ((address & 0xFF)
                + "." + ((address >> 8) & 0xFF)
                + "." + ((address >> 16) & 0xFF)
                + "." + ((address >> 24) & 0xFF));
    }
    return "";
}

Solution

  • You may try setting up default network to your connected wifi hotspot so that all future sockets will be created using this wifi network only.

    val request = NetworkRequest.Builder()
    request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    connectivityManager.registerNetworkCallback(request.build(), object : NetworkCallback() {   
    override fun onAvailable(network: Network) {
    currentNetwork = network
    val success = ConnectivityManager.setProcessDefaultNetwork(network)
    }
    })