Some background:
I have an Android app that uses a 3G or 4G data connection. But it also connects to a wifi hotspot to transfer some data between the hotspot device and the app.
What I want to do: create a socket connection to this wifi hotspot and send/receive data over this socket.
I added the following code to ensure that we use the wifi hotspot wifi while creating a socket (else it sometimes ends up using the data connection):
android.net.wifi.WifiManager wm = (android.net.wifi.WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
This seems to be fine. However, I see issues while trying to connect to the remote server address. Here's the code I am using:
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
InetAddress localAddress = InetAddress.getByName(ip);
socket = new Socket(serverAddr,SERVERPORT,localAddress,0);
I am using a socket call that connects to a remote server address from a local address (the wifi connection wifi address obtained as above). I am setting the local port to 0 since that will allow the socket to pick any local available port. However, when I do this, I get a connection timed out error all the time.
java.net.ConnectException: failed to connect to /A.B.C.D (port 3003) from /A.B.C.E (port 48492): connect failed: ETIMEDOUT (Connection timed out)
I'm sure there's no issue with the server socket code, since I am able to connect to the server if I do not use a local address. The below code always works:
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
However, I cannot use it always because I want data and wifi to be ON simultaneously and the above code does not guarantee that it will always use the wifi connection to connect. (in fact it rarely works)
I also tried manually doing a bind to the local wifi ip address and some random port. and then doing a socket connect. But that did not work either.
I initially thought that the port number does not get closed properly if I use it once. But then I noticed that this issue often occurs even when I open the app for the first time. I even tried setting port to 0 (ephemeral port) to ensure it picks up any available port.
Any suggestions. If there's a better way to solve this problem, pl let me know.
Thanks in advance.