Search code examples
androidsocketsnetwork-programmingtcpandroid-networking

Send a string to wifi connected device return the EHOSTUNREACH (No route to host) in android


So , the flow of the application is ,

first , I use my android phone to connect a device (which is a server) through wifi, then , I would like to send a string to that device, and that is all.

The problem is , when I try to send like this

new Thread(new Runnable() {
    @Override
    public void run() {
        try {

            Socket socket = new Socket("192.168.8.101",2001);
            DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
            DOS.writeUTF("61");
            socket.close();

        } catch (Exception e) {    
            final String error = e.getMessage();
            runOnUiThread(new Runnable(){

                @Override
                public void run() {
                    Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show();
                }

            });

            Log.d("test1",e.getMessage());
            e.printStackTrace();
        }

}).start();

it return the failed to connect to /192.168.8.101 (port 2001) : connect failed EHOSTUNREACH (No route to host) in the exception

How to fix that , and by programming or using some way , are there any way to check whether the ip and port is correct ? Thanks


Solution

  • Make sure you turn off the firewalls on that port.

    To make sure IP is up we usually ping that machine.

    There is a tool called wireshark that taps the packets coming to your machine. So put you send function in while 1000 loop and pump messages. Turn wiresahrak at the server and see if you are able to get the packets there.

    There are lots of other programs which can connects to sockets. take a sample java program and try to get connected to the other socket. If it does, your android stuff will also do.