Reputation: 21
I'm having a problem with creating a socket. The error is as follows
java.net.ConnectException: failed to connect to /192.168.1.103 (port 23): connect failed: ENETUNREACH (Network is unreachable)
Here is part of my code
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + wifiName + "\"";
wifiConfiguration.preSharedKey = "\"" + password + "\"";
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.addNetwork(wifiConfiguration);
if (networkId != -1)
{
wifiManager.enableNetwork(networkId, true);
new Thread(new GetMacThread()).start();
}
class GetMacThread implements Runnable{
private Socket socket;
private int portNumber = 23;
private String myIP = "192.168.1.103";
@Override
public void run()
{
try {
socket = new Socket(myIP, portNumber);
System.out.println("Socket Thread:"+socket);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
I'm pretty sure that it is not network problem (IP and port are good, I have also added permissions in manifest) because I tested it with connected WIFI network and commented line wifiManager.enableNetwork(networkId, true)
and socket was made properly. Program was working then. So the problem is that, it is working only with previously turned on WiFi.
I also tried first to check wifi connection with ConnectivityManager before creating socket but it changed nothing.
Have you got any ideas why socket fails in this particular order?
Upvotes: 2
Views: 5618
Reputation: 13
The method ConnectivityManager.bindProcessToNetwork() helped me in a similar case. You can find additional information here - https://android-developers.googleblog.com/2016/07/connecting-your-app-to-wi-fi-device.html.
Upvotes: 1