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

时间:2013-10-28 10:29:01

标签: android c++ sockets tcp

我想在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();
}

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。解决方案包含两个.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(); 

SocketDll.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); 
}