C ++ TCP代理和套接字编程

时间:2011-11-29 07:17:18

标签: sockets visual-c++ tcp proxy daemon

好的,过去十个小时我一直在搜索网络(字面意思),但似乎没有人有一个教程解释如何在Windows中创建C ++代理服务器。有几次我遇到了仅适用于UNIX的功能,这是一次令人沮丧的经历。我是套接字编程的新手,但我需要在48小时内完成。现在似乎不可能。

该计划的要求:

  • 守护程序侦听指定端口号上的TCP连接。
  • 当新客户端发起TCP连接请求时,守护程序接受 请求并与新客户端建立TCP连接。
  • 守护程序分叉专用于处理新进程的子进程 客户端。
  • 子进程与之间的预分配端口建立TCP连接 实际目标服务器。
  • 子进程陷入了一个循环,它充当了一个中间人 在客户端和客户端之间交换数据(读/写或写/读) 目标服务器。
  • 一旦孩子被分叉,守护进程就会继续监听 额外的TCP连接。

我已经运行了一个提供的winsock客户端和程序,以便更好地了解套接字是如何工作的,但它让我无处可去。 pid_t不适用于Windows,因此分叉是不可能的(或者我从10小时的净淘洗中收集到了)。

如果您能够指出我能够将Internet Explorer的代理设置(IP和端口号功能)与程序结合使用以产生重定向到另一台服务器的网页,那么这将是一个很好的选择。

/* client.c - code for example client program that uses TCP */


#ifndef unix
#include<winsock2.h>
#include <windows.h>
#include <winsock.h> 
#pragma comment(lib, "ws2_32.lib")


#else
#define closesocket close
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#endif

#include <stdio.h>
#include <string.h>
#include <iostream>

#define PROTOPORT       5193            /* default protocol port number */

extern "C";
char    localhost[] =   "localhost";    /* default host name            */
#define QLEN 6                          /* size of request queue        */

int     visits      =   0;              /* counts client connections    */
/*------------------------------------------------------------------------
 * Program:   client
 *
 * Purpose:   allocate a socket, connect to a server, and print all output
 *
 * Syntax:    client [ host [port] ]
 *
 *               host  - name of a computer on which server is executing
 *               port  - protocol port number server is using
 *
 * Note:      Both arguments are optional.  If no host name is specified,
 *            the client uses "localhost"; if no protocol port is
 *            specified, the client uses the default given by PROTOPORT.
 *
 *------------------------------------------------------------------------
 */
int main(int argc, char *argv[])
{               
        struct  hostent  *ptrh;  /* pointer to a host table entry       */
        struct  protoent *ptrp;  /* pointer to a protocol table entry   */
        struct  sockaddr_in sad; /* structure to hold an IP address     */
        int     port;            /* protocol port number                */
        char    *host;           /* pointer to host name                */
        int     n;               /* number of characters read           */
        char    buf[1000];       /* buffer for data from the server     */
        struct  sockaddr_in cad; /* structure to hold client's address  */
        int     sd, sd2;         /* socket descriptors                  */
        int     alen;            /* length of address                   */

#ifdef WIN32
        WSADATA wsaData;
        WSAStartup(0x0101, &wsaData);
#endif
        memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
        sad.sin_family = AF_INET;         /* set family to Internet     */
        sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address   */

        /* Check command-line argument for protocol port and extract    */
        /* port number if one is specified.  Otherwise, use the default */
        /* port value given by constant PROTOPORT                       */

        if (argc > 2) {                 /* if protocol port specified   */
                port = atoi(argv[2]);   /* convert to binary            */
        } else {
                port = PROTOPORT;       /* use default port number      */
        }
            if (port > 0)                   /* test for legal value         */
                sad.sin_port = htons((u_short)port);
        else {                          /* print error message and exit */
                fprintf(stderr,"bad port number %s\n",argv[2]);
                exit(1);

         if (argc > 1) {                 /* if argument specified        */
                port = atoi(argv[1]);   /* convert argument to binary   */
        } else {
            port = PROTOPORT;       /* use default port number      */
    }
    if (port > 0)                   /* test for illegal value       */
            sad.sin_port = htons((u_short)port);
    else {                          /* print error message and exit */
            fprintf(stderr,"bad port number %s\n",argv[1]);
            exit(1);
    }

    /* Map TCP transport protocol name to protocol number */
    (int)(ptrp = getprotobyname("tcp"));
    if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
            fprintf(stderr, "cannot map \"tcp\" to protocol number");
            exit(1);
    }

    /* Check host argument and assign host name. */

    if (argc > 1) {
            host = argv[1];         /* if host argument specified   */
    } else {
            host = localhost;
    }

    /* Convert host name to equivalent IP address and copy to sad. */

    ptrh = gethostbyname(host);
    if ( ((char *)ptrh) == NULL ) {
            fprintf(stderr,"invalid host: %s\n", host);
            exit(1);
    }
    memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);

    /* Map TCP transport protocol name to protocol number. */
    (int)(ptrp = getprotobyname("tcp"));
    if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
            fprintf(stderr, "cannot map \"tcp\" to protocol number");
            exit(1);
    }

    /* Create a socket. */

    sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
    if (sd < 0) {
            fprintf(stderr, "socket creation failed\n");
            exit(1);
    }

    /* Connect the socket to the specified server. */
    connect(sd, (struct sockaddr *)&sad, sizeof(sad));
    if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
            fprintf(stderr,"connect failed\n");
            exit(1);
    }

     /* Bind a local address to the socket */
    bind(sd, (struct sockaddr *)&sad, sizeof(sad));
    if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
            fprintf(stderr,"bind failed\n");
            exit(1);
    }

    /* Specify size of request queue */
    listen(sd, QLEN);
    if (listen(sd, QLEN) < 0) {
            fprintf(stderr,"listen failed\n");
            exit(1);
    }

    /* Repeatedly read data from socket and write to user's screen. */

    n = recv(sd, buf, sizeof(buf), 0);
    while (n > 0) {
            int _write(int fd, const void *buffer, unsigned int count);
            n = recv(sd, buf, sizeof(buf), 0);
    }

     /* Main server loop - accept and handle requests */

    while (1) {
            alen = sizeof(cad);
    printf("\nI'm waiting for connections ...");
    fflush(stdout);
            if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
                    fprintf(stderr, "accept failed\n");
                    exit(1);
            }
    printf("\nI received one connection.\n");
    fflush(stdout);
            visits++;
            sprintf_s(buf,"This server has been contacted %d time%s\n",
                    visits,visits==1?".":"s.");
            send(sd2,buf,strlen(buf),0);
    printf("\nI sent the client a string.\n");
    fflush(stdout);
            closesocket(sd2);
    }


    /* Close the socket. */

    closesocket(sd);

    /* Terminate the client program gracefully. */

    exit(0);
}
}

如果你已经做到这一点,我感谢你的警惕。祝我好运......

0 个答案:

没有答案