Android connect to tethering socket Android connect to tethering socket android android

Android connect to tethering socket


By testing it turns out the connection cannot be established on the tethering device.

But if we reverse the process and open a serversocket on the connected client. And connect to it from the tethering device, it will work.

So reversing the communication is the answer.


Server Side

class ServerThread implements Runnable {    public void run() {        socket = new Socket();        try {            serverSocket = new ServerSocket(SERVERPORT);        } catch (IOException e) {            e.printStackTrace();        }        while (!Thread.currentThread().isInterrupted()) {            try {                    socket = serverSocket.accept();                CommunicationThread commThread = new CommunicationThread(socket);                new Thread(commThread).start();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

Client Side

class ClientThread implements Runnable {    @Override    public void run() {        try {            socket = new Socket();            InetSocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVERPORT);            socket.connect(socketAddress);            CommunicationThread commThread = new CommunicationThread(socket);            new Thread(commThread).start();        } catch (UnknownHostException e1) {            e1.printStackTrace();        } catch (IOException e1) {            e1.printStackTrace();        }    }}


In a tethered wifi connection, connection provider can not work as a client. So we need to implement a bidirectional tcp socket connection. Use a server socket with a port number in device which is in tethering mode. This device act as a server. In client device use socket to access the client port with IP address.