javaandroidmodbus-tcp

Accessing ethernet port connected to android phone


I am trying to build an app for modbus tcp/ip client on my android device. I've attached a USB to ethernet port converter and I'm trying to communicate through my laptop as a server. I'm not able to connect to the network with the error saying:

java.net.ConnectionException: failed to connect to /192.168.29.244 (port 502) from /::(port 0): connect failed: ENETUNREACH (network is unreachable)

I'm trying that by keeping the phone on Wifi and data off/airplane mode so as not to confuse it with Wifi signals.

It works flawlessly when my android device and laptop are on the same wireless network, but when attempting a wired connection with the laptop, it fails with the above-mentioned error. But when I tried a wired connection with the network switch on which I've my entire wifi internet, it worked.

Not able to figure out the problem.

Table

Thread t1 = new Thread(() -> {
                /* The important instances of the classes mentioned before */
                con = null; //the connection

                /* Variables for storing the parameters */
                int port = Integer.parseInt(etPort.getText().toString());

                String ip = etIP.getText().toString();
                try {
                    InetAddress addr = InetAddress.getByName(ip);//the slave's address

                    con = new TCPMasterConnection(addr);
                    con.setPort(port);
                    con.setTimeout(500);
                    Log.d("Connection parameters", "Timeout: " + con.getTimeout() + " Port: " + port);
                    con.connect();
                    runOnUiThread(() -> {
                        tv.setText("Connected!!!");
                        connect.setText("Disconnect");
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("Error!", e.toString());
                    runOnUiThread(() -> {
                        tv.setText(e.toString());
                    });
                }
            });
            if (connect.getText().equals("Connect"))
                t1.start();
            else {
                Log.d("In diconnect", "Coonection closed!");
                con.close();
                connect.setText("Connect");
                tv.setText("Disconnected!!!");
            }

Solution

  • I am not sure that I completely understand the question, but I do think that it has something to do with you connecting your phone directly to your laptop.

    When you connect your phone to a network device, such as router or switch, it get's the IP address from the DHCP server, but when you connect it directly to your laptop, your phone simply doesn't have any IP address, unless you set up a static address, so it's not visible on the network.