一个简单的Proxy代理服务器的源代码!

类别:VC语言 点击:0 评论:0 推荐:

 

#include <windows.h>
#include <stdio.h>

#define PROXY_IP "xxx.xxx.xxx.xxx"
#define PROXY_PORT 1080

#define DEST_IP "xxx.xxx.xxx.xxx"
#define DEST_PORT 8888

#define LOCAL_IP "xxx.xxx.xxx.xxx"
#define LOCAL_PORT 6666

int main()
{   
    int fd, fd_udp;   
    struct sockaddr_in name;
    WSADATA wsaData;   
    char buf[100];   
    int len;
    int i;
    if(WSAStartup(MAKEWORD( 2, 2 ), &wsaData ))       
        return 1;
    if((fd_udp = socket(AF_INET, SOCK_DGRAM, 0)) == -1)       
      return 1;   
    if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)       
      return 1;   
    memset(&name, 0, sizeof(name));   
    name.sin_family = AF_INET;   
    name.sin_addr.s_addr = inet_addr(PROXY_IP);   
    name.sin_port = htons(PROXY_PORT);   
    if(connect(fd, (struct sockaddr*)&name, sizeof(name)) != 0)       
        return 1;   
    buf[0] = 5;   
    buf[1] = 1;   
    buf[2] = 0;   
    send(fd, buf, 3, 0);   
    recv(fd, buf, 2, 0);   
    if(buf[0] != 5 || buf[1] != 0)       
        return 1;
    buf[0] = 5; /* protocol version */ 
    buf[1] = 3; /* command UDP associate */   
    buf[2] = 0; /* reserved */   
    buf[3] = 1; /* address type IP v4 */   
    len = sizeof(name);
    memset(&name, 0, sizeof(name));
    name.sin_family = AF_INET;   
    name.sin_addr.s_addr = inet_addr(LOCAL_IP);   
    name.sin_port = htons(LOCAL_PORT);
    bind(fd_udp,(struct sockaddr *)&name,len);
    *(unsigned int*)&buf[4] = inet_addr(LOCAL_IP);//name.sin_addr.s_addr;   
    *(unsigned short*)&buf[8] = htons(LOCAL_PORT);   
    send(fd, buf, 10, 0);   
    recv(fd, buf, 10, 0);   
    if(buf[0] != 5)       
      return 11;   
    memset(&name, 0, sizeof(name));   
    name.sin_family = AF_INET;   
    name.sin_addr.s_addr = *(int*)&buf[4];   
    name.sin_port = (*(short*)&buf[8]);   
    connect(fd_udp, (struct sockaddr *)&name, sizeof(name));   
    for(i = 0; i <100; i++)
    {
        buf[0] = 0; /* reserved */       
        buf[1] = 0; /* reserved */
        buf[2] = 0; /* standalone packet */       
        buf[3] = 1; /* address type IP v4 */       
        *(unsigned long*)&buf[4] = inet_addr(DEST_IP);       
        *(unsigned short*)&buf[8] = htons(DEST_PORT);       
        *(unsigned int*)&buf[10] = i;       
        send(fd_udp, buf, 14, 0);       
        recv(fd_udp, buf, 14, 0);       
        printf("udp received: %d\n", *(int*)&buf[10]);   
    }   
    closesocket(fd_udp);   
    closesocket(fd);   
    WSACleanup();   
    return 0;
}

本文地址:http://com.8s8s.com/it/it3705.htm