I have an android application which (over the network) communicates with a desktop server application (Both programmed in Java and GUI based). For now to test, i simply have a way to specify the socket on the android phone. However, in the future when i release the application, i want it to be able to attempt connecting to the server by itself.
Some ideas i have had so far is getting the IP address of the phone, and then looping through a class C address space on the same port and seeing if any of those sockets connect. Do you guys have anything else you can suggest?
Also, what is the best way to get the phone’s IP Address in Android? I have a way but it only works on android 2.3 and lower…on ICS it completely flops and gives random gibberish. Here it is:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception ex) {
}
return null;
}
Looping over C-class network needless overkill. I wouldn’t use it unless as an utter last resort. Your user may have A-class network (10.x.x.x, popular in workplaces), or B-class, because… he likes it so 😉
The better way would be to utilise broadcast address (or multicast if you prefer, but it’s a bit more work). You may implement simple discovery protocol for your application based on UDP datagrams. In such case your server listens to the broadcast port, e.g UDP 192.168.0.255:6666 (port of your choosing) and responds to any activity by sending the IP:PORT it’s listening to to the requester.
Client can then display available servers and ask to which one the user wants to connect, then connect to TCP port provided in the answer (I assume client-server connection is TCP, but it can be anything, the idea is the same).