First you can check what your IP address is:
public InetAddress getIpAddress() { InetAddress inetAddress = null; InetAddress myAddr = null; try { for (Enumeration < NetworkInterface > networkInterface = NetworkInterface .getNetworkInterfaces(); networkInterface.hasMoreElements();) { NetworkInterface singleInterface = networkInterface.nextElement(); for (Enumeration < InetAddress > IpAddresses = singleInterface.getInetAddresses(); IpAddresses .hasMoreElements();) { inetAddress = IpAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && (singleInterface.getDisplayName() .contains("wlan0") || singleInterface.getDisplayName().contains("eth0") || singleInterface.getDisplayName().contains("ap0"))) { myAddr = inetAddress; } } } } catch (SocketException ex) { Log.e(TAG, ex.toString()); } return myAddr; }
and I used this IP for translation as follows:
public InetAddress getBroadcast(InetAddress inetAddr) { NetworkInterface temp; InetAddress iAddr = null; try { temp = NetworkInterface.getByInetAddress(inetAddr); List < InterfaceAddress > addresses = temp.getInterfaceAddresses(); for (InterfaceAddress inetAddress: addresses) iAddr = inetAddress.getBroadcast(); Log.d(TAG, "iAddr=" + iAddr); return iAddr; } catch (SocketException e) { e.printStackTrace(); Log.d(TAG, "getBroadcast" + e.getMessage()); } return null; }
This can be done, of course, in one way, but in my implementation it was useful to split it into two methods.
To determine if Wifi Tether is enabled, you can use this code:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); Method[] wmMethods = wifi.getClass().getDeclaredMethods(); for (Method method: wmMethods) { if (method.getName().equals("isWifiApEnabled")) { try { if ((Boolean) method.invoke(wifi)) { isInetConnOn = true; iNetMode = 2; } else { Log.d(TAG, "WifiTether off"); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
If client devices need to know if the server device is a mobile access point, a specific IP address can be used. As far as I know, all Tethering devices have the same address 192.168.43.1. This is the same on Android 2.3 and 4.+, tested on many phones and tablets. Of course, this is not the best solution, but it is fast. In my application, client devices check (sends a packet to this address) and the response to my server devices in a predefined form, for example, "yesIamInTheterModeIamYourServer".
MP23
source share