如何使用'adb forward tcp:8081 tcp:8082'等C++进行端口转发

how to do port forwarding with C++ like 'adb forward tcp:8081 tcp:8082'

本文关键字:tcp 转发 C++ 8082 forward adb 何使用 8081      更新时间:2023-10-16

我想在PC和手机之间建立连接。PC作为客户端,PC端代码用C++或C编写。另一方面,手机充当服务器,手机端代码是用Android编写的。这两个设备通过USB电缆连接,它们用于相互通信,这意味着服务器(手机)没有固定IP。为了两个设备可以通信,我们必须在客户端做端口转发(我猜)。我已经用Java(代码如下)实现了客户端,但我对C++/C知之甚少,我不知道如何用C++/C实现端口转发,或者我不知道用C++/C实现客户端,希望有人可以帮助我。

try {
    // how to realize sentence below with C++
    Runtime.getRuntime().exec("adb forward tcp:8081 tcp:8082");
    Thread.sleep(TIME_SLEEP);
} catch (Exception e) {
    e.printStackTrace();
}
Socket socket = null;
try {
    InetAddress serveraddr = null;
    serveraddr = InetAddress.getByName("127.0.0.1");
    socket = new Socket(serveraddr, 8081);      
} catch (UnknownHostException e1) {
    e1.printStackTrace();
} catch (Exception e2) {
    e2.printStackTrace();
}

我已经解决了这个问题。解决方案包含两个 .h 文件和一个 cpp 文件。代码列表如下:

InitSock.h

#include <winsock2.h>
#include <stdlib.h> 
#include <conio.h> 
#include <stdio.h> 
#pragma comment(lib, "WS2_32")  // link to WS2_32.lib
class CInitSock     
{
public:
    CInitSock(BYTE minorVer = 2, BYTE majorVer = 2)
    {
        // init WS2_32.dll
        WSADATA wsaData;
        WORD sockVersion = MAKEWORD(minorVer, majorVer);
        if(::WSAStartup(sockVersion, &wsaData) != 0)
        {
            exit(0);
        }
    }
    ~CInitSock()
    {   
        ::WSACleanup(); 
    }
};

SocketDll.h

#pragma once 
#define DLL_EXPORT __declspec(dllexport)  
extern "C" DLL_EXPORT void startSocket(); 

套接字Dll.cpp

#include "InitSock.h"
#include <stdio.h>
#include <iostream>  
#include <process.h>
using namespace std;
CInitSock initSock;     // init lib Winsock
#include "SocketDll.h" 
void startSocket() 
{ 
    // port forwarding(mapping)
    system("adb forward tcp:8081 tcp:8082");
    // new socket
    SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(s == INVALID_SOCKET)
    {
        printf(" Failed socket() /n");
        return;
    }
    sockaddr_in servAddr; 
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(8081);
    // set up ip
    servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    if(::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)) == -1)
    {
        printf(" Failed connect() /n");
        return;
    } else {
        cout << "connect successed!" << endl;
    }
    char buff[256];
    char szText[256] ;
    while(TRUE)
    {
        // send datas to server
        cin>>szText ;
        szText[255] = '/0';
        ::send(s, szText, strlen(szText), 0) ;
        // receiver datas from server
        int nRecv = ::recv(s, buff, 256, 0);
        if(nRecv > 0)
        {
            buff[nRecv] = '/0';
            printf("data received:%s/n", buff);
        }
    }
    // close socket
    ::closesocket(s); 
}