1

I have a new problem, i couldn't resolve the last : Multicast : using joinGroup on a multicast socket (java/android) packet isn't received

So I tryed another way. I'm launching a server on my computer and the client as an app on my androiddevice. But when I'm trying to connect to my computer i get the error :

java.net.ConnectException: failed to connect to /192.168.137.1 (port 54321): connect failed: ENETUNREACH

But i verify i can ping from my computer to the device and inversively when my firewall is turned off. I don't understand why it can't work with socket when it works by pinging.

My code :

Server

public class Server implements Runnable

{
private final ServerSocket serverSocket;

public Server() throws IOException {
    //serverSocket = new ServerSocket(Constant.SERVER_PORT);
    serverSocket = new ServerSocket(Constant.SERVER_PORT, 1000, InetAddress.getLocalHost());
}

public static void main(String[] args) throws IOException {
    new Server().open();
}

private void open()
{
    Socket client;
    BufferedReader in;
    PrintWriter out;

    while (true) {
        try {

            // TODO: 25/03/2017 Threaded Service
            client = serverSocket.accept();
            System.out.println("Client accepted");

            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream());
            Thread.sleep(200);
            out.println("CONNECTED");
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Override
public void run() {
    open();
    Scanner sc = new Scanner(System.in);
    sc.next();
    while(true);
}

My Thread which connect to the server in my activity :

    public class Home extends AppCompatActivity {

private HandlerConnectionRunnable handlerConnectionMsg;
private HandlerNetwork handlerNetwork;

private boolean connectionOver = false;

private InetAddress hotspotIP;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    handlerConnectionMsg = new HandlerConnectionRunnable();
    new Thread(new ConnectionRunnable()).start();
}

public void sendData(View view)
{
    if (!connectionOver)
        return;
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

public void getFirstMessage()
{
    new Thread(new FirstMessage()).start();
}

private class ConnectionRunnable implements Runnable
{
    private static final String CONNECTION_MESSAGE_KEY = "connection_message";
    private static final String CURRENT_AP             = "current_ap";

    private static final int ACTIVATING_WIFI  = 0;
    private static final int CONNECTION_AP    = 1;
    private static final int CONNECTED        = 2;
    private static final int CONNECTION_ERROR = 3;

    private Message msg;

    @Override
    public void run()
    {
        msg = handlerConnectionMsg.obtainMessage();
        Bundle b = new Bundle();

        // Get the wifi manager
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        // Enable the wifi
        boolean wasEnabled = wifiManager.isWifiEnabled();

        msg = handlerConnectionMsg.obtainMessage();
        b = new Bundle();
        b.putInt("connection_message", ACTIVATING_WIFI);
        msg.setData(b);
        handlerConnectionMsg.sendMessage(msg);

        wifiManager.setWifiEnabled(true);
        // Wait for the connection
        while(!wifiManager.isWifiEnabled());

        boolean ret = true;

        // Connect to the access point and disable the connection to others
        if (wifiManager.isWifiEnabled() && wifiManager.startScan())
        {
            msg = handlerConnectionMsg.obtainMessage();
            b = new Bundle();
            b.putInt("connection_message", CONNECTION_AP);
            msg.setData(b);
            handlerConnectionMsg.sendMessage(msg);

            ret = connectToAP(wifiManager, "trainee_hotspot_test", "d0nt3nt3rThis");
            //ret = connectToAP(wifiManager, "trainee_test", "12345678");
        }

        if (!ret)
        {
            msg = handlerConnectionMsg.obtainMessage();
            b = new Bundle();
            b.putInt("connection_message", CONNECTION_ERROR);
            msg.setData(b);
            handlerConnectionMsg.sendMessage(msg);

            return;
        }

        /*
        WifiManager.MulticastLock multicastLock = wifiManager.createMulticastLock("mydebuginfo");
        //multicastLock.setReferenceCounted(true);
        multicastLock.acquire();
        */

        //WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        //int ipAddress = wifiInfo.getIpAddress();
        int ipAddress = wifiManager.getDhcpInfo().serverAddress;

        try {
            hotspotIP = InetAddress.getByName(convertToIp(ipAddress));
            //System.out.println(hotspotIP.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }



        msg = handlerConnectionMsg.obtainMessage();
        b = new Bundle();
        // Valid connection
        b.putInt("connection_message", CONNECTED);
        b.putString("current_ap", wifiManager.getConnectionInfo().getSSID());
        msg.setData(b);
        handlerConnectionMsg.sendMessage(msg);

    }

    private String convertToIp(int ipAddress) throws UnknownHostException {
        byte[] address = { (byte)(0xff & ipAddress),
                (byte)(0xff & (ipAddress >> 8)),
                (byte)(0xff & (ipAddress >> 16)),
                (byte)(0xff & (ipAddress >> 24)) };

        return InetAddress.getByAddress(address).getHostAddress();
    }

    private boolean connectToAP(WifiManager wifi, String name, String pass)
    {
        // Create a new wifiConfiguration object
        WifiConfiguration wifiConfig = new WifiConfiguration();

        // Add informations to it
        wifiConfig.SSID = String.format("\"%s\"", name);
        wifiConfig.preSharedKey = String.format("\"%s\"", pass);

        // We add this configuration to the wifi manager and get the id
        int netId = wifi.addNetwork(wifiConfig);
        // Disconnect from the current AP
        wifi.disconnect();
        // Enable the hotspot with given SSID if it exists
        boolean status = wifi.enableNetwork(netId, true);
        wifi.reconnect();

        return status;
    }
}

private class HandlerConnectionRunnable extends Handler
{
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        Home.this.connectionOver = true;

        Bundle b = msg.getData();

        int connectionMsg = b.getInt(ConnectionRunnable.CONNECTION_MESSAGE_KEY);

        switch (connectionMsg)
        {
            case ConnectionRunnable.ACTIVATING_WIFI:
                Toast.makeText(Home.this, "The wifi will be activated", Toast.LENGTH_SHORT).show();
                break;
            case ConnectionRunnable.CONNECTION_AP:
                Toast.makeText(Home.this, "The connection to the current access point will be disabled", Toast.LENGTH_LONG).show();
                break;
            case ConnectionRunnable.CONNECTION_ERROR:
                Toast.makeText(Home.this, "The connection wasn't possible", Toast.LENGTH_SHORT).show();
                break;
            case ConnectionRunnable.CONNECTED:
                Toast.makeText(Home.this, "Connected to : " + b.getString(ConnectionRunnable.CURRENT_AP), Toast.LENGTH_SHORT).show();
                getFirstMessage();
                break;
        }
    }
}

private class HandlerNetwork extends Handler
{
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        Toast.makeText(Home.this, msg.getData().getString("NETWORK"), Toast.LENGTH_LONG).show();
    }
}

private class FirstMessage implements Runnable
{
    @Override
    public void run() {
        Socket socket = null;
        socket = new Socket();

        try {
            //socket = new Socket(hotspotIP, Constant.SERVER_PORT);
            socket = new Socket();

            socket.connect(new InetSocketAddress(hotspotIP, Constant.SERVER_PORT));

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());

            String read = in.readLine();

            Message msg = handlerNetwork.obtainMessage();
            Bundle b = new Bundle();
            b.putString("NETWORK", "CONNECTED");
            msg.setData(b);
            handlerNetwork.sendMessage(msg);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

}

Thanks all for replying

Have a good day

Update

I forgot to say that the phone and the computer are on the same network because the phone is connected to the hotspot that is my computer.

Update 2

I put the entire class for the Client in order to not forget any important part of code.

Update 3 Afer using the link of Ray, I obtain :

Display name: ip6tnl0 Name: ip6tnl0 Display name: wlan0 Name: wlan0 Display name: tunl0 Name: tunl0 Display name: sit0 Name: sit0 Display name: p2p0 Name: p2p0 InetAddress: /fe80::73:8dff:fefa:c4a3%p2p0%11 Display name: ifb0 Name: ifb0 Display name: ifb1 Name: ifb1 Display name: lo InetAddress: /::1%1%1 InetAddress: /127.0.0.1 Display name: ccmni2 Name: ccmni2 0Display name: ccmni0 Name: ccmni0 Display name: ccmni1 Name: ccmni1

Community
  • 1
  • 1
Rikoo
  • 31
  • 4
  • You are only messing around with wifi manager code. Which should not be needed at all. Code for a client for your server is missing completely. So wnere is this about? – greenapps Apr 18 '17 at 11:08
  • Sorry i forgot a part of my code, i edit this right now – Rikoo Apr 18 '17 at 11:34
  • `put the entire class for the Client in order to not forget any important part of code.`. Well i will not dig through that all. I already asked you why we had to look at that wifi manager code. I had expected you to remove it. I am out. – greenapps Apr 18 '17 at 11:51
  • did you verify that the inet addresses for both the client and the server are the same? – Ray Tayek Apr 18 '17 at 11:57
  • @greenapps sorry i didn't understand this, i can remove this part if you want but i do some stuff that are used later( like hotspotIp variable) – Rikoo Apr 18 '17 at 12:29
  • @Ray Yes i printed the address that is used by the device and it's the same that my PC, and when i ping it works well, no packets are lost – Rikoo Apr 18 '17 at 12:31
  • try reversing the byte order in convertToIp() - i suspect that the ipadress is in network byte order. – Ray Tayek Apr 18 '17 at 14:55
  • It doesn't work, instead of having the error which say i can't connect to 192.168.137.1 , the error say i can't connect to 1.137.168.192 – Rikoo Apr 19 '17 at 07:32
  • maybe try using the normal java interfaces (https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html). and make sure that you can use that i p address – Ray Tayek Apr 19 '17 at 17:25
  • Thanks i will try it later ^^ – Rikoo Apr 20 '17 at 08:30
  • I used your link, I add what I obtained in an update. I don't know what i have to conclude :/ – Rikoo Apr 21 '17 at 08:22

0 Answers0