Is there a programmatic way for an Android device to check the IP address of the computer to which it is connected to while the phone is in tether mode? Also, the WiFi and data have to be turned off.
Asked
Active
Viewed 843 times
1 Answers
0
If you're checking the public IP address of your computer, then you'll need to ask an outside server: https://stackoverflow.com/a/2939223/2201238
If you're looking for the local IP address of the computer with respect to the tethered network, you'll need to find the gateway IP of that network. It's possible to do this by finding the system property dhcp.interface_name_here.gateway
. Where you'd replace interface_name_here
with another value, like wlan0
(wifi), rmnet[012345]
(cell or usb tethering), p2p
(wifi direct), or if you're using HoRNDIS rndis0
.
@Nullable
public String getTetheredGatewayIp() {
NetworkInterface tetheredNic = getTetheredNetworkInterface();
try {
Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties");
return (String) systemPropertiesClass
.getMethod("get", String.class)
.invoke(systemPropertiesClass, "dhcp." + tetheredNic.getName() + ".gateway");
} catch (Exception ignore) {}
return null;
}
// Find the NetworkInterface of any 'rndis' NIC:
@Nullable
private NetworkInterface getTetheredNetworkInterface() {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface nic = networkInterfaces.nextElement();
if (nic.isUp() && !nic.isLoopback() && nic.getName().contains("rndis")) {
return nic;
}
}
return null;
}

iamreptar
- 1,461
- 16
- 29
-
What is `SystemProperties`, its not found in android. I am trying to do USB tethering. – develop1 Sep 07 '17 at 22:34
-
Ah, the SystemProperties class has the @hide javadoc. I've updated the code to use reflection. You can also execute the "getprop" process and read the output from it's stream. – iamreptar Sep 07 '17 at 22:49
-
Does not work just returns an empty string. Tested it for both `rndis` and `rmnet`. – develop1 Sep 08 '17 at 00:39