linux c++ tcp端口转发

229次阅读
没有评论

共计 2022 个字符,预计需要花费 6 分钟才能阅读完成。

linux tcp端口转发,转发本地8888端口tcp数据到本地120.0.0.1:5201端口,简单程序,可能存在bug

#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fstream>
#include <iostream> 
#include <thread>
#define BUFFER_SIZE 1024 * 20
using namespace std;
void copyBuffer(int srcConn,int desConn){
    char Buffer[BUFFER_SIZE];
    bzero(Buffer,BUFFER_SIZE);
    ssize_t  readSize,writeSize = 0;
    while((readSize = recv(srcConn,&Buffer,BUFFER_SIZE,MSG_NOSIGNAL)) > 0){
        //cout << "read size:" << readSize << endl;
        //发送读取到的数据给服务端
        if((writeSize = send(desConn,Buffer,readSize,MSG_NOSIGNAL)) <= 0)
            break;
        //cout << "write size:" << writeSize << endl;
    }
}
void thread_task(int srconn){
    //tcp客户端
    int sockfd;
    int len;
    struct sockaddr_in address;
    int result;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(5201);
    len = sizeof(address);
    result = connect(sockfd,  (struct sockaddr *)&address, len);
    if(result == -1){
        perror("oops: client1");
    }

    cout << "开始写回数据" << endl;
    //写入接收到的数据
    thread t1(copyBuffer,srconn,sockfd);
    thread t2(copyBuffer,sockfd,srconn);
    t1.join();
    t2.join();
    //读取客户端的数据
    close(sockfd);
    close(srconn);
}
int main(){

    //创建tcp服务端
    int server_sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(server_sockfd < 0){
        perror("socket");
        return -1;
    }
    // 声明并初始化一个服务器端的socket地址结构
    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8888);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    //设置端口重用
    int opt = 1;
    setsockopt(server_sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    //绑定地址
    if(bind(server_sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr)) < 0){
        perror("bind");
        return -1;
    }
    //监听
    if(listen(server_sockfd,5) < 0){
        perror("listen");
        return -1;
    }
    while (1)
    {
        struct sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        int client_sockfd = accept(server_sockfd,(struct sockaddr*)&client_addr,&len);
        if(client_sockfd < 0){
            perror("faile");
            return -1;
        }
        //发送client_sockfd到线程处理数据
        std::cout << "开启线程" << endl;
        thread t (thread_task,client_sockfd);
        t.detach();        
    }
    return 1;
}

 

正文完
 
admin
版权声明:本站原创文章,由 admin 2022-02-17发表,共计2022字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码