Search code examples
pythonandroidc++socketsadb

Issue when connecting a socket application over a port forwarded over adb


I was developing an application which has a server on the PC and client as an android device connected over adb (USB). I have setup port forwarding by: adb forward tcp:5100 tcp:5100

Whenever I'm trying to run my python server over this it says :

server.bind(("127.0.0.1", 5100))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

Here is my server code:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
        #server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    
        server.bind(("127.0.0.1", 5100))
        server.listen()
        
        print("Waitng for client Sockets " + socket.gethostname())
        conn, address = server.accept()
        with conn:
            print("Connected to framework", address)
            while True:
                recvdStr = conn.recv(1024)
                if not recvdStr:
                    break
                print("Received: " + recvdStr.decode())

Client code:

#include <jni.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_testframeworktest_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";

    int client = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(5100);
    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    connect(client, (sockaddr*)&serverAddr, sizeof(sockaddr));
    send(client, "sending test string", strlen("sending test string"), 0);
    send(client, "", strlen(""), 0);
    return env->NewStringUTF(hello.c_str());
}

After enabling port forwarding, netstat-an shows my port in this state:

 TCP    127.0.0.1:5100         0.0.0.0:0              LISTENING

Solution

  • To have the python server code and the android client side to talk each other you should use adb reverse instead of forward. This is the adb command that you should use

    adb reverse tcp:5100 tcp:5100