#include <winsock>
#include <iostream>
#include <string>
int main( int argc, char * argv[] )
{
SOCKET spojeni;
WSADATA info;
sockaddr_in local;
local.sin_family=AF_INET;
local.sin_addr.s_addr=INADDR_ANY;
local.sin_port=htons(62000);
if(WSAStartup(0x101,&info)!=0){std::cout<<"WSAStartup error";};
spojeni = socket(AF_INET,SOCK_STREAM,0);
if(spojeni==INVALID_SOCKET){std::cout<<"Socket error";}
if(bind(spojeni,(sockaddr*)&local,sizeof(local))!=0){std::cout<<"Bind error";};
if(listen(spojeni,0)!=0){std::cout<<"Listen error";};
SOCKET client;
sockaddr_in client_info;
int client_size = sizeof(client_info);
client = accept(spojeni,(sockaddr*)&client_info,&client_size);
char text[100000];
int text_len=999;
int prijato;
int poslano;
char neco[1000];
char prijem[550];
poslano = recv(client,text,text_len,0);
char *ahoj = strstr(text,"");
int pos=strcspn(ahoj," ");
strncpy(neco,ahoj,pos);
neco[pos]=' ';
std::cout << neco;
SOCKET server;
WSAData server_data;
sockaddr_in server_info;
hostent *hp;
int addr=inet_addr("172.16.1.48");
hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
server_info.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server_info.sin_family=AF_INET;
server_info.sin_port=htons(500);
server=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(server==INVALID_SOCKET){std::cout<<"Socket error (server)";}
connect(server,(struct sockaddr*)&server_info,sizeof(server_info));
send(server,text,poslano,0);
std::cout << text;
poslano=50;
while((poslano > 0) && (poslano <550)){
poslano = recv(server,prijem,512,0);
std::cout << "-";
prijem[poslano]='\0';
send(client,prijem,poslano,0);
std::cout <<prijem;
std::cout << "*" << poslano;
}
std::cout << "+";
closesocket(server);
std::cout << "+" << "\n\r";
closesocket(client);
closesocket(spojeni);
return 0;
}
Socks Proxy Server
прокси должен подключаться к заранее прописанному адресу.
Вот есть код, но он не совсем рабочий, при коннекте клиена к серверу есть контакт, а обратно нет (тоесть клиент послал запрос на соединение, сервер одобрил но у клиенту это не дошло, потом при каких либо действиях выдают ерроры 10060 и 10061)
Код:
нашел вроде рабочий только под visual c++, помогите перевести:
Код:
#include <windows.h>
// НАСТРОЙКА ПАРАМЕТРОВ
#define IN_PORT 62000
#define OUT_IP "172.16.1.48"
#define OUT_PORT 55500
#define MAX_DATA 100
#define MAXCONN 1000
#define IDE_MSG 110
#define WM_ASYNC_CLIENTEVENT WM_USER+1
#define WM_ASYNC_PROXYEVENT WM_USER+10
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
void ConnectToProxy(SOCKET);
SOCKET hListenSockTCP = INVALID_SOCKET;
SOCKADDR_IN myaddrTCP,proxyaddrTCP;
char buf[MAX_DATA];
SOCKET sockets[MAXCONN];
HWND hwndMain;
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrevInst,LPSTR szCmdLine,int nCmdShow)
{
WSADATA stWSADataTCPIP;
if(WSAStartup(0x0101, &stWSADataTCPIP)) MessageBox(0,"WSAStartup error !","NET ERROR!!!",0);
ZeroMemory(sockets,sizeof(sockets));
WNDCLASS wc;
memset(&wc,0,sizeof(WNDCLASS));
wc.style = CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ;
wc.lpfnWndProc = (WNDPROC)MainWndProc;
wc.hInstance = hInst;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName = "CProxy";
wc.lpszMenuName = NULL;
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
if (!RegisterClass(&wc)) return 0;
hwndMain=CreateWindow("CProxy","ProxyExample", WS_MINIMIZEBOX|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_MAXIMIZEBOX|WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME, CW_USEDEFAULT,0,CW_USEDEFAULT,0, NULL, NULL, hInst, NULL);
ShowWindow(hwndMain,SW_SHOW);
hListenSockTCP = socket (AF_INET,SOCK_STREAM,0);
myaddrTCP.sin_family = AF_INET;
myaddrTCP.sin_addr.s_addr = htonl (INADDR_ANY);
myaddrTCP.sin_port = htons (IN_PORT);
if(bind(hListenSockTCP,(LPSOCKADDR)&myaddrTCP, sizeof(struct sockaddr))) { MessageBox(hwndMain,"This port in use!","BIND TCP ERROR!!!",0);}
if (listen (hListenSockTCP, 5)) MessageBox(hwndMain,"listen error!","ERROR!!!",0);
WSAAsyncSelect (hListenSockTCP,hwndMain,WM_ASYNC_CLIENTEVENT,FD_ACCEPT|FD_READ|FD_CLOSE);
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
return 0;
}
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
WORD WSAEvent;
int i;
DWORD currentsock;
switch (msg)
{
case WM_COMMAND:
break;
case WM_DESTROY:
PostQuitMessage(0); // 10xu4yourtime
break;
case WM_ASYNC_CLIENTEVENT: // Сообщения про события сокетов, подключенных к клиенту...
currentsock = wParam;
WSAEvent = WSAGETSELECTEVENT (lParam);
switch (WSAEvent)
{
case FD_CLOSE :
shutdown(sockets[currentsock],1);
closesocket(currentsock);
return 0;
case FD_READ:
// ПЕРЕНАПРАВЛЕНИЕ ДАННЫХ (redirect). Берем от клиента, посылаем на сервер.
i=recv(currentsock, buf, MAX_DATA, 0);
send(sockets[currentsock], buf, i, 0); // и отправляем...
return 0;
case FD_ACCEPT:
ConnectToProxy(accept(hListenSockTCP,NULL,NULL));
return 0;
}
break;
case WM_ASYNC_PROXYEVENT:
// Найдем соответствующий дескриптор.
for (i=0;i<MAXCONN;i++)
if (sockets == wParam) { currentsock=i; break; }
WSAEvent = WSAGETSELECTEVENT (lParam);
switch (WSAEvent)
{
// Произошло подключение к удаленному хосту
case FD_CONNECT :
i=WSAGETSELECTERROR(lParam);
if (i!=0)
{
shutdown(currentsock,1);
closesocket(sockets[currentsock]);
sockets[currentsock]=INVALID_SOCKET;
}
return 0;
// Сервер нас отрубает ...
case FD_CLOSE :
shutdown(currentsock,1);
closesocket(sockets[currentsock]); sockets[currentsock]=INVALID_SOCKET;
return 0;
// Перенаправление данных клиенту
case FD_READ:
i=recv(sockets[currentsock], buf, MAX_DATA, 0);
send(currentsock,buf, i, 0);
return 0;
}
break;
}
return DefWindowProc(hwnd,msg,wParam,lParam);
}
// Connect to PROXY Connect to PROXY Connect to PROXY Connect to PROXY Connect to PROXY Connect to PROXY
void ConnectToProxy(SOCKET nofsock)
{
SOCKADDR_IN rmaddr;
rmaddr.sin_family = AF_INET;
rmaddr.sin_addr.s_addr = inet_addr(OUT_IP);
rmaddr.sin_port = htons (OUT_PORT);
sockets[nofsock] = socket (AF_INET,SOCK_STREAM,0); if(INVALID_SOCKET == sockets[nofsock]) MessageBox(0,"INVALID_SOCKET","ERROR!!!",0);
WSAAsyncSelect (sockets[nofsock],hwndMain,WM_ASYNC_PROXYEVENT, FD_CONNECT|FD_READ|FD_CLOSE);
connect (sockets[nofsock], (struct sockaddr *)&rmaddr,sizeof(rmaddr));
return; // Connect OK
}
// НАСТРОЙКА ПАРАМЕТРОВ
#define IN_PORT 62000
#define OUT_IP "172.16.1.48"
#define OUT_PORT 55500
#define MAX_DATA 100
#define MAXCONN 1000
#define IDE_MSG 110
#define WM_ASYNC_CLIENTEVENT WM_USER+1
#define WM_ASYNC_PROXYEVENT WM_USER+10
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
void ConnectToProxy(SOCKET);
SOCKET hListenSockTCP = INVALID_SOCKET;
SOCKADDR_IN myaddrTCP,proxyaddrTCP;
char buf[MAX_DATA];
SOCKET sockets[MAXCONN];
HWND hwndMain;
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrevInst,LPSTR szCmdLine,int nCmdShow)
{
WSADATA stWSADataTCPIP;
if(WSAStartup(0x0101, &stWSADataTCPIP)) MessageBox(0,"WSAStartup error !","NET ERROR!!!",0);
ZeroMemory(sockets,sizeof(sockets));
WNDCLASS wc;
memset(&wc,0,sizeof(WNDCLASS));
wc.style = CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ;
wc.lpfnWndProc = (WNDPROC)MainWndProc;
wc.hInstance = hInst;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName = "CProxy";
wc.lpszMenuName = NULL;
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
if (!RegisterClass(&wc)) return 0;
hwndMain=CreateWindow("CProxy","ProxyExample", WS_MINIMIZEBOX|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_MAXIMIZEBOX|WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME, CW_USEDEFAULT,0,CW_USEDEFAULT,0, NULL, NULL, hInst, NULL);
ShowWindow(hwndMain,SW_SHOW);
hListenSockTCP = socket (AF_INET,SOCK_STREAM,0);
myaddrTCP.sin_family = AF_INET;
myaddrTCP.sin_addr.s_addr = htonl (INADDR_ANY);
myaddrTCP.sin_port = htons (IN_PORT);
if(bind(hListenSockTCP,(LPSOCKADDR)&myaddrTCP, sizeof(struct sockaddr))) { MessageBox(hwndMain,"This port in use!","BIND TCP ERROR!!!",0);}
if (listen (hListenSockTCP, 5)) MessageBox(hwndMain,"listen error!","ERROR!!!",0);
WSAAsyncSelect (hListenSockTCP,hwndMain,WM_ASYNC_CLIENTEVENT,FD_ACCEPT|FD_READ|FD_CLOSE);
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
return 0;
}
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
WORD WSAEvent;
int i;
DWORD currentsock;
switch (msg)
{
case WM_COMMAND:
break;
case WM_DESTROY:
PostQuitMessage(0); // 10xu4yourtime
break;
case WM_ASYNC_CLIENTEVENT: // Сообщения про события сокетов, подключенных к клиенту...
currentsock = wParam;
WSAEvent = WSAGETSELECTEVENT (lParam);
switch (WSAEvent)
{
case FD_CLOSE :
shutdown(sockets[currentsock],1);
closesocket(currentsock);
return 0;
case FD_READ:
// ПЕРЕНАПРАВЛЕНИЕ ДАННЫХ (redirect). Берем от клиента, посылаем на сервер.
i=recv(currentsock, buf, MAX_DATA, 0);
send(sockets[currentsock], buf, i, 0); // и отправляем...
return 0;
case FD_ACCEPT:
ConnectToProxy(accept(hListenSockTCP,NULL,NULL));
return 0;
}
break;
case WM_ASYNC_PROXYEVENT:
// Найдем соответствующий дескриптор.
for (i=0;i<MAXCONN;i++)
if (sockets == wParam) { currentsock=i; break; }
WSAEvent = WSAGETSELECTEVENT (lParam);
switch (WSAEvent)
{
// Произошло подключение к удаленному хосту
case FD_CONNECT :
i=WSAGETSELECTERROR(lParam);
if (i!=0)
{
shutdown(currentsock,1);
closesocket(sockets[currentsock]);
sockets[currentsock]=INVALID_SOCKET;
}
return 0;
// Сервер нас отрубает ...
case FD_CLOSE :
shutdown(currentsock,1);
closesocket(sockets[currentsock]); sockets[currentsock]=INVALID_SOCKET;
return 0;
// Перенаправление данных клиенту
case FD_READ:
i=recv(sockets[currentsock], buf, MAX_DATA, 0);
send(currentsock,buf, i, 0);
return 0;
}
break;
}
return DefWindowProc(hwnd,msg,wParam,lParam);
}
// Connect to PROXY Connect to PROXY Connect to PROXY Connect to PROXY Connect to PROXY Connect to PROXY
void ConnectToProxy(SOCKET nofsock)
{
SOCKADDR_IN rmaddr;
rmaddr.sin_family = AF_INET;
rmaddr.sin_addr.s_addr = inet_addr(OUT_IP);
rmaddr.sin_port = htons (OUT_PORT);
sockets[nofsock] = socket (AF_INET,SOCK_STREAM,0); if(INVALID_SOCKET == sockets[nofsock]) MessageBox(0,"INVALID_SOCKET","ERROR!!!",0);
WSAAsyncSelect (sockets[nofsock],hwndMain,WM_ASYNC_PROXYEVENT, FD_CONNECT|FD_READ|FD_CLOSE);
connect (sockets[nofsock], (struct sockaddr *)&rmaddr,sizeof(rmaddr));
return; // Connect OK
}
а в деле выдает general sock failure
Код:
#include <windows.h>
#include <vcl.h>
#include <iostream>
#define NOAUTH 0
#define GSSAPI 0//Íå ðåàëèçîâàíî
#define USERNAME_PASSWORD 2
#define AUTHSCHEME USERNAME_PASSWORD
struct CONN_PARAM
{
SOCKET sockSession;
SOCKET sockClient;
};
bool InitSockets();
void SendNegativeResponse(SOCKET sock,int iError);
void SendPositiveResponse(SOCKET sockSession,SOCKET sockClient);
DWORD WINAPI SessionEstablished(LPVOID lpConnParam);
DWORD WINAPI Session(LPVOID lpParameter);
int main(void)
{
if (InitSockets())
{
std::cout << "Initialization successfull\n";
}
SOCKET socketListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (socketListen!=INVALID_SOCKET)
{
std::cout << "Listen socket created\n";
}
sockaddr_in a;
struct hostent *h;
h=gethostbyname("localhost");
h=gethostbyname(h->h_name);
a.sin_family=AF_INET;
a.sin_port=htons(60000);
memcpy(&(a.sin_addr.S_un.S_addr),h->h_addr,sizeof(int));
if (0!=bind(socketListen,(struct sockaddr *)&a,sizeof(a)))
{
std::cout << "Cannot bind socket!\n";
return -2;
}
if(0==listen(socketListen,50)){std::cout << "PROXY STARTED\n";}
while (true)
{
sockaddr sa;
int iLength=sizeof(sa);
SOCKET sockSession=accept(socketListen,&sa,&iLength);
if (sockSession!=INVALID_SOCKET)
{
std::cout << "Client socket created\n";
}
DWORD dwThread;
CreateThread(NULL,0,Session,(LPVOID)sockSession,0,&dwThread);
}
}
bool InitSockets()
{
WSADATA wsadata;
if (0==WSAStartup(2,&wsadata)) return true;
else return false;
}
void SendNegativeResponse(SOCKET sock,int iError)
{
char ResponsePacket[10];
ResponsePacket[0]=5;
switch (iError)
{
case WSAENETDOWN:
ResponsePacket[1]=3;//Network unreachable
break;
case WSAENETUNREACH:
ResponsePacket[1]=3;//Network unreachable
break;
case WSAECONNREFUSED:
ResponsePacket[1]=5;//Connection refused
break;
case WSAETIMEDOUT:
ResponsePacket[1]=4;//Host unreachable
break;
default:
ResponsePacket[1]=1;//general SOCKS server failure
}
ResponsePacket[2]=0;
ResponsePacket[3]=1;
hostent *h=gethostbyname("localhost");
h=gethostbyname(h->h_name);
*((int *)(ResponsePacket+4))=*((int *)(h->h_addr));
*(short *)(ResponsePacket+8)=htons(4000);
int nReceived;
nReceived=send(sock,ResponsePacket,10,0);
closesocket(sock);
}
void SendPositiveResponse(SOCKET sockSession,SOCKET sockClient)
{
char ResponsePacket[10];
ResponsePacket[0]=5;
ResponsePacket[1]=0;
ResponsePacket[2]=0;
ResponsePacket[3]=1;
hostent *h=gethostbyname("localhost");
h=gethostbyname(h->h_name);
*((int *)(ResponsePacket+4))=*((int *)(h->h_addr));
sockaddr_in sa;
int iSize=sizeof(sa);
getsockname(sockClient,(sockaddr *)&sa,&iSize);
*(short *)(ResponsePacket+8)=sa.sin_port;
int nReceived=send(sockSession,ResponsePacket,10,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
std::cout << "Response error\n";
}
}
DWORD WINAPI SessionEstablished(LPVOID lpConnParam)
{
CONN_PARAM *pcp=(CONN_PARAM *)lpConnParam;
SOCKET sockSession=pcp->sockSession;
SOCKET sockClient=pcp->sockClient;
int nReceived;
while (true)
{
char c;
nReceived=recv(sockClient,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
std::cout << "Error then receiving from server\n";
closesocket(sockSession);
return 2;
}
nReceived=send(sockSession,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
std::cout << "Error then sending to client\n";
closesocket(sockSession);
return 2;
}
}
return 0;
}
DWORD WINAPI Session(LPVOID lpParameter)
{
SOCKET sockSession=(SOCKET)lpParameter;
char cVersion;
int nReceived=recv(sockSession,&cVersion,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cMethodsCount;
nReceived=recv(sockSession,&cMethodsCount,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *cMethods=new char[cMethodsCount];
for (int i=0;i<cMethodsCount;i++)
{
nReceived=recv(sockSession,&cMethods,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
switch (AUTHSCHEME)
{
case NOAUTH:
{
char *packet=new char[2];
packet[0]=5;
if (cVersion!=5) {packet[1]=(char)0xFF; std::cout << "Unsupported SOCKS Version\n";}
else {packet[1]=0; std::cout << "SOCKS Version accepted\n";}
nReceived=send(sockSession,packet,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
case USERNAME_PASSWORD:
{
char *packet=new char[2];
packet[0]=5;
if (cVersion!=5) {packet[1]=(char)0xFF; std::cout << "Unsupported SOCKS Version\n";}
else {packet[1]=2; std::cout << "SOCKS Version accepted\n";}
nReceived=send(sockSession,packet,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cVersion;
nReceived=recv(sockSession,&cVersion,1,0);
if (SOCKET_ERROR==nReceived)
{
std::cout << "Authorization required\n";
closesocket(sockSession);
return 2;
}
char cNameLength;
nReceived=recv(sockSession,&cNameLength,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *sName=new char[cNameLength+1];
nReceived=recv(sockSession,sName,cNameLength,0);
sName[cNameLength]=0;
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cPassLength;
nReceived=recv(sockSession,&cPassLength,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *sPass=new char[cPassLength+1];
nReceived=recv(sockSession,sPass,cPassLength,0);
sPass[cPassLength]=0;
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
if (!strcmp(sName,"zergnm"))
if (!strcmp(sPass,"qwerty"))
{
char *Packet=new char[2];
Packet[0]=1;
Packet[1]=0;
nReceived=send(sockSession,Packet,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
else
{
char *Packet=new char[2];
Packet[0]=1;
Packet[1]=0;
nReceived=send(sockSession,Packet,2,0);
std::cout << "Bad password\n";
closesocket(sockSession);
return 3;
}
else
{
char *Packet=new char[2];
Packet[0]=1;
Packet[1]=0;
nReceived=send(sockSession,Packet,2,0);
std::cout << "Bad login\n";
closesocket(sockSession);
return 3;
}
}
/*
case GSSAPI:
//Åùå íå ñäåëàíî
closesocket(sockSession);
return 4;
*/
}
nReceived=recv(sockSession,&cVersion,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cCommand;
nReceived=recv(sockSession,&cCommand,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cReserved;
nReceived=recv(sockSession,&cReserved,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cAddrType;
nReceived=recv(sockSession,&cAddrType,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *Address;
switch (cAddrType)
{
case 1://IPv4
{
Address=new char[4];
nReceived=recv(sockSession,Address,4,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
break;
}
case 3:
{
char iLength;
nReceived=recv(sockSession,&iLength,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
Address=new char[iLength+1];
nReceived=recv(sockSession,Address,iLength,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
Address[iLength]=0;
break;
}
}
short iPort;
nReceived=recv(sockSession,(char *)&iPort,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockClient != INVALID_SOCKET){std::cout << "Server socket created\n";}
switch (cCommand)
{
case 1:
{
std::cout << "Connecting...\n";
//Ñîåäèíÿåìñÿ
sockaddr_in a;
a.sin_family=AF_INET;
a.sin_port=iPort;
//Åñëè àäðåñ äàí êàê FQDN, òî íàäî åãî îòðåñîëâèòü
if (cAddrType==3)
{
hostent *h=gethostbyname(Address);
memcpy(&(a.sin_addr.S_un.S_addr),h->h_addr,sizeof(int));
}
else
a.sin_addr.S_un.S_addr=*(int *)Address;
//Ïðîáóåì ïîäêëþ÷èòüñÿ
nReceived=connect(sockClient,(sockaddr *)&a,sizeof(a));
if (nReceived)
{
std::cout << "Cannot connect to server";
SendNegativeResponse(sockSession,nReceived);
return -1;
}
SendPositiveResponse(sockSession,sockClient);
std::cout << "Connected";
CONN_PARAM cp;
cp.sockClient=sockClient;
cp.sockSession=sockSession;
DWORD dwThreadID;
CreateThread(NULL,0,SessionEstablished,&cp,0,&dwThreadID);
}
break;
case 2:
{
sockaddr_in a;
a.sin_family=AF_INET;
a.sin_port=iPort;
if (cAddrType==3)
{
hostent *h=gethostbyname(Address);
memcpy(&(a.sin_addr.S_un.S_addr),h->h_addr,sizeof(int));
}
else
a.sin_addr.S_un.S_addr=*(int *)Address;
nReceived=bind(sockClient,(sockaddr *)&a,sizeof(a));
if (nReceived)
{
SendNegativeResponse(sockSession,nReceived);
return -1;
}
nReceived=listen(sockClient,5);
if (nReceived)
{
SendNegativeResponse(sockSession,nReceived);
return -1;
}
SendPositiveResponse(sockSession,sockClient);
int iSize=sizeof(a);
sockClient=accept(sockClient,(sockaddr *)&a,&iSize);
if (sockClient==INVALID_SOCKET)
{
SendNegativeResponse(sockSession,nReceived);
return -1;
}
SendPositiveResponse(sockSession,sockClient);
}
}
CONN_PARAM cp;
cp.sockClient=sockClient;
cp.sockSession=sockSession;
DWORD dwThreadID;
CreateThread(NULL,0,SessionEstablished,&cp,0,&dwThreadID);
while (true)
{
char c;
nReceived=recv(sockSession,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
nReceived=send(sockClient,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
return 0;
}
#include <vcl.h>
#include <iostream>
#define NOAUTH 0
#define GSSAPI 0//Íå ðåàëèçîâàíî
#define USERNAME_PASSWORD 2
#define AUTHSCHEME USERNAME_PASSWORD
struct CONN_PARAM
{
SOCKET sockSession;
SOCKET sockClient;
};
bool InitSockets();
void SendNegativeResponse(SOCKET sock,int iError);
void SendPositiveResponse(SOCKET sockSession,SOCKET sockClient);
DWORD WINAPI SessionEstablished(LPVOID lpConnParam);
DWORD WINAPI Session(LPVOID lpParameter);
int main(void)
{
if (InitSockets())
{
std::cout << "Initialization successfull\n";
}
SOCKET socketListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (socketListen!=INVALID_SOCKET)
{
std::cout << "Listen socket created\n";
}
sockaddr_in a;
struct hostent *h;
h=gethostbyname("localhost");
h=gethostbyname(h->h_name);
a.sin_family=AF_INET;
a.sin_port=htons(60000);
memcpy(&(a.sin_addr.S_un.S_addr),h->h_addr,sizeof(int));
if (0!=bind(socketListen,(struct sockaddr *)&a,sizeof(a)))
{
std::cout << "Cannot bind socket!\n";
return -2;
}
if(0==listen(socketListen,50)){std::cout << "PROXY STARTED\n";}
while (true)
{
sockaddr sa;
int iLength=sizeof(sa);
SOCKET sockSession=accept(socketListen,&sa,&iLength);
if (sockSession!=INVALID_SOCKET)
{
std::cout << "Client socket created\n";
}
DWORD dwThread;
CreateThread(NULL,0,Session,(LPVOID)sockSession,0,&dwThread);
}
}
bool InitSockets()
{
WSADATA wsadata;
if (0==WSAStartup(2,&wsadata)) return true;
else return false;
}
void SendNegativeResponse(SOCKET sock,int iError)
{
char ResponsePacket[10];
ResponsePacket[0]=5;
switch (iError)
{
case WSAENETDOWN:
ResponsePacket[1]=3;//Network unreachable
break;
case WSAENETUNREACH:
ResponsePacket[1]=3;//Network unreachable
break;
case WSAECONNREFUSED:
ResponsePacket[1]=5;//Connection refused
break;
case WSAETIMEDOUT:
ResponsePacket[1]=4;//Host unreachable
break;
default:
ResponsePacket[1]=1;//general SOCKS server failure
}
ResponsePacket[2]=0;
ResponsePacket[3]=1;
hostent *h=gethostbyname("localhost");
h=gethostbyname(h->h_name);
*((int *)(ResponsePacket+4))=*((int *)(h->h_addr));
*(short *)(ResponsePacket+8)=htons(4000);
int nReceived;
nReceived=send(sock,ResponsePacket,10,0);
closesocket(sock);
}
void SendPositiveResponse(SOCKET sockSession,SOCKET sockClient)
{
char ResponsePacket[10];
ResponsePacket[0]=5;
ResponsePacket[1]=0;
ResponsePacket[2]=0;
ResponsePacket[3]=1;
hostent *h=gethostbyname("localhost");
h=gethostbyname(h->h_name);
*((int *)(ResponsePacket+4))=*((int *)(h->h_addr));
sockaddr_in sa;
int iSize=sizeof(sa);
getsockname(sockClient,(sockaddr *)&sa,&iSize);
*(short *)(ResponsePacket+8)=sa.sin_port;
int nReceived=send(sockSession,ResponsePacket,10,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
std::cout << "Response error\n";
}
}
DWORD WINAPI SessionEstablished(LPVOID lpConnParam)
{
CONN_PARAM *pcp=(CONN_PARAM *)lpConnParam;
SOCKET sockSession=pcp->sockSession;
SOCKET sockClient=pcp->sockClient;
int nReceived;
while (true)
{
char c;
nReceived=recv(sockClient,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
std::cout << "Error then receiving from server\n";
closesocket(sockSession);
return 2;
}
nReceived=send(sockSession,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
std::cout << "Error then sending to client\n";
closesocket(sockSession);
return 2;
}
}
return 0;
}
DWORD WINAPI Session(LPVOID lpParameter)
{
SOCKET sockSession=(SOCKET)lpParameter;
char cVersion;
int nReceived=recv(sockSession,&cVersion,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cMethodsCount;
nReceived=recv(sockSession,&cMethodsCount,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *cMethods=new char[cMethodsCount];
for (int i=0;i<cMethodsCount;i++)
{
nReceived=recv(sockSession,&cMethods,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
switch (AUTHSCHEME)
{
case NOAUTH:
{
char *packet=new char[2];
packet[0]=5;
if (cVersion!=5) {packet[1]=(char)0xFF; std::cout << "Unsupported SOCKS Version\n";}
else {packet[1]=0; std::cout << "SOCKS Version accepted\n";}
nReceived=send(sockSession,packet,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
case USERNAME_PASSWORD:
{
char *packet=new char[2];
packet[0]=5;
if (cVersion!=5) {packet[1]=(char)0xFF; std::cout << "Unsupported SOCKS Version\n";}
else {packet[1]=2; std::cout << "SOCKS Version accepted\n";}
nReceived=send(sockSession,packet,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cVersion;
nReceived=recv(sockSession,&cVersion,1,0);
if (SOCKET_ERROR==nReceived)
{
std::cout << "Authorization required\n";
closesocket(sockSession);
return 2;
}
char cNameLength;
nReceived=recv(sockSession,&cNameLength,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *sName=new char[cNameLength+1];
nReceived=recv(sockSession,sName,cNameLength,0);
sName[cNameLength]=0;
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cPassLength;
nReceived=recv(sockSession,&cPassLength,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *sPass=new char[cPassLength+1];
nReceived=recv(sockSession,sPass,cPassLength,0);
sPass[cPassLength]=0;
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
if (!strcmp(sName,"zergnm"))
if (!strcmp(sPass,"qwerty"))
{
char *Packet=new char[2];
Packet[0]=1;
Packet[1]=0;
nReceived=send(sockSession,Packet,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
else
{
char *Packet=new char[2];
Packet[0]=1;
Packet[1]=0;
nReceived=send(sockSession,Packet,2,0);
std::cout << "Bad password\n";
closesocket(sockSession);
return 3;
}
else
{
char *Packet=new char[2];
Packet[0]=1;
Packet[1]=0;
nReceived=send(sockSession,Packet,2,0);
std::cout << "Bad login\n";
closesocket(sockSession);
return 3;
}
}
/*
case GSSAPI:
//Åùå íå ñäåëàíî
closesocket(sockSession);
return 4;
*/
}
nReceived=recv(sockSession,&cVersion,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cCommand;
nReceived=recv(sockSession,&cCommand,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cReserved;
nReceived=recv(sockSession,&cReserved,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char cAddrType;
nReceived=recv(sockSession,&cAddrType,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
char *Address;
switch (cAddrType)
{
case 1://IPv4
{
Address=new char[4];
nReceived=recv(sockSession,Address,4,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
break;
}
case 3:
{
char iLength;
nReceived=recv(sockSession,&iLength,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
Address=new char[iLength+1];
nReceived=recv(sockSession,Address,iLength,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
Address[iLength]=0;
break;
}
}
short iPort;
nReceived=recv(sockSession,(char *)&iPort,2,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockClient != INVALID_SOCKET){std::cout << "Server socket created\n";}
switch (cCommand)
{
case 1:
{
std::cout << "Connecting...\n";
//Ñîåäèíÿåìñÿ
sockaddr_in a;
a.sin_family=AF_INET;
a.sin_port=iPort;
//Åñëè àäðåñ äàí êàê FQDN, òî íàäî åãî îòðåñîëâèòü
if (cAddrType==3)
{
hostent *h=gethostbyname(Address);
memcpy(&(a.sin_addr.S_un.S_addr),h->h_addr,sizeof(int));
}
else
a.sin_addr.S_un.S_addr=*(int *)Address;
//Ïðîáóåì ïîäêëþ÷èòüñÿ
nReceived=connect(sockClient,(sockaddr *)&a,sizeof(a));
if (nReceived)
{
std::cout << "Cannot connect to server";
SendNegativeResponse(sockSession,nReceived);
return -1;
}
SendPositiveResponse(sockSession,sockClient);
std::cout << "Connected";
CONN_PARAM cp;
cp.sockClient=sockClient;
cp.sockSession=sockSession;
DWORD dwThreadID;
CreateThread(NULL,0,SessionEstablished,&cp,0,&dwThreadID);
}
break;
case 2:
{
sockaddr_in a;
a.sin_family=AF_INET;
a.sin_port=iPort;
if (cAddrType==3)
{
hostent *h=gethostbyname(Address);
memcpy(&(a.sin_addr.S_un.S_addr),h->h_addr,sizeof(int));
}
else
a.sin_addr.S_un.S_addr=*(int *)Address;
nReceived=bind(sockClient,(sockaddr *)&a,sizeof(a));
if (nReceived)
{
SendNegativeResponse(sockSession,nReceived);
return -1;
}
nReceived=listen(sockClient,5);
if (nReceived)
{
SendNegativeResponse(sockSession,nReceived);
return -1;
}
SendPositiveResponse(sockSession,sockClient);
int iSize=sizeof(a);
sockClient=accept(sockClient,(sockaddr *)&a,&iSize);
if (sockClient==INVALID_SOCKET)
{
SendNegativeResponse(sockSession,nReceived);
return -1;
}
SendPositiveResponse(sockSession,sockClient);
}
}
CONN_PARAM cp;
cp.sockClient=sockClient;
cp.sockSession=sockSession;
DWORD dwThreadID;
CreateThread(NULL,0,SessionEstablished,&cp,0,&dwThreadID);
while (true)
{
char c;
nReceived=recv(sockSession,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
nReceived=send(sockClient,&c,1,0);
if (SOCKET_ERROR==nReceived)
{
closesocket(sockSession);
return 2;
}
}
return 0;
}
Обьясните пожалуйста как его собрать? Желательно по пунктам, пробовал скомпилировать в 5 ой версии,выдаёт горы ошибок.
ты делай console application
Большое спасибо. Не могли бы вы немного обьяснить код. Где задаётся адрес/порт удалённого компьютера?
У этого кода много недоработок, это так сказать основа.
Если будет охота доделать, выложи плиз доработки)
while(true) это бесконечный цикл, там сокет принимает заявки на подключение, и для каждого в отжельности создает поток (Session).
В этом session прокси запращивает версию соксов, логин, пароль (если требуется) в данном случае логин zergnm пароль qwerty. Потом он ждет комманду, когда пришла комманда на подключение он запращивает удаленный аддрес и подключается к нему, в этом потоке while(true)
обеспечивает передачу от клиента у серверу. Если соединение произошло создается новый поток SessionEstablished. там While(true)
обеспечивает передчу от сервера к клиенту. SendNegative и SentPositive REsponse это функции необходимые для правельной работы соксов.
Надеюсь все понятно)