I use an Android box with an ethernet interface.
The box is connected to network using ethernet.
The serversocket.GetMyIp returns correct IP, both with wifi enabled and disabled.
When I enable tethering(Hotspot) then serversocket.GetMyIp returns the tethering IP (192.168.43.1)
Anyone have an idea how I can get correct ethernet IP with tethering enabled?
Note that it returns a correct ip address. Just not the one you are interested in.
Try this code:
B4X:
Sub Activity_Create(FirstTime As Boolean)
Dim jo As JavaObject
jo.InitializeContext
jo.RunMethod("PrintAllInterfaces", Null)
End Sub
#if JAVA
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
public static void PrintAllInterfaces() throws Exception {
for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
BA.Log("" + e.nextElement());
}
}
#End If
Here er the log with Hotspot disabled:
[ip6tnl0][5]
[tunl0][3]
[sit0][4]
[eth0][2][/fd79:a696:734b:0:2c0a:72ff:fed0:6bab%2%2][/fe80::2c0a:72ff:fed0:6bab%eth0%2][/192.168.1.160]
[lo][1][/::1%1%1][/127.0.0.1]
Serversocket returns 192.168.1.160
and with Hotspot enabled:
[ip6tnl0][5]
[wlan0][31][/fe80::1a:11ff:feff:fa65%wlan0%31][/192.168.43.1]
[tunl0][3]
[sit0][4]
[eth0][2][/fd79:a696:734b:0:2c0a:72ff:fed0:6bab%2%2][/fe80::2c0a:72ff:fed0:6bab%eth0%2][/192.168.1.160]
[lo][1][/::1%1%1][/127.0.0.1]
You can use this code to get the ip address of a specific interface:
B4X:
Sub Activity_Create(FirstTime As Boolean)
Dim jo As JavaObject
jo.InitializeContext
Log(jo.RunMethod("getIp", Array("wlan0"))) 'change to eth0 to get the ethernet address
End Sub
#if JAVA
import java.net.InetAddress;
import java.net.Inet6Address;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
public static String getIp(String interfaceName) throws Exception {
for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
NetworkInterface ni = e.nextElement();
if (ni.getName().equals(interfaceName)) {
Enumeration<InetAddress> en2 = ni.getInetAddresses();
while (en2.hasMoreElements()) {
InetAddress ia = en2.nextElement();
if (!ia.isLoopbackAddress()) {
if ((ia instanceof Inet6Address) == false) {
return ia.getHostAddress();
}
}
}
}
}
return "";
}
#End If