I've written a thread using java.net.SocketServer
to listen on a particular port. It works fine in the android simulator (using port forwarding). I'm planning to connect over wifi to this port when the app is being used. However, the SocketServer
documentation says that if you don't supply an InetAddress
, the server listens on localhost.
Am I correct that if I do not supply the address, I will not be able to get a connection over wifi? How can I get the InetAddress
of the wifi connection to pass to the SocketServer
?
When you create a ServerSocket you listen to a port on the localhost. It's up to you if you want to nominate your own local host address.
Read these two articles:
Remember to have a WiFi lock and the appropriate permissions.
You can try the following code.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
private String getIPAddress() throws SocketException {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null || !info.isConnected()){
return null;
}
switch (info.getType()) {
case ConnectivityManager.TYPE_WIFI: {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi == null) break;
WifiInfo wifi_info = wifi.getConnectionInfo();
String ipAddress = intToIp(wifi_info.getIpAddress());
return ipAddress;
}
case ConnectivityManager.TYPE_MOBILE: {
Enumeration<NetworkInterface> interfaceEnumerations = NetworkInterface.getNetworkInterfaces();
while(interfaceEnumerations.hasMoreElements()){
NetworkInterface interfac = interfaceEnumerations.nextElement();
Enumeration<InetAddress> inetAddresses = interfac.getInetAddresses();
while(inetAddresses.hasMoreElements()){
InetAddress address = inetAddresses.nextElement();
if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) {
String addressIp = address.getHostAddress();
if(TextUtils.isEmpty(addressIp) || !addressIp.matches("(\\d{1,3}.){3}\\d{1,3}")) continue;
return addressIp;
}
}
}
break;
}
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With