Shouldn't this code work? (select())
Well, this is basically a proxy.
It takes things from a program that is running on port 15777 and the puts it out to host on port 15776, but sence I added the
select() witch is needed. It hasn't been working right. Any help?
#include <windows.h> //Required for socket init
#include <iostream>
#include <sys/time.h>
using namespace std;
int main(){
char buf[256];
char uua[256];
WSAData wsdata; //Declare WSAData
WORD wsver=MAKEWORD(2, 0); //We want Winsock 2.0
WSAStartup(wsver, &wsdata);
//WSA starting code
//Hosting thing.
SOCKET Szocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
SOCKADDR_IN serverInf;
serverInf.sin_family=AF_INET;
serverInf.sin_addr.s_addr=INADDR_ANY;
serverInf.sin_port=htons(15776);
bind(Szocket,(SOCKADDR*)(&serverInf),sizeof(serverInf));
listen(Szocket,1);
SOCKET TempSock=SOCKET_ERROR;
while(TempSock==SOCKET_ERROR)
{
std::cout<<"Waiting for incoming connections...\r\n";
TempSock=accept(Szocket,NULL,NULL);
}
u_long iMode=1;
ioctlsocket(Szocket,FIONBIO,&iMode);
Szocket=TempSock;
std::cout<<"Client connected!\r\n\r\n";
SOCKET kSock=socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in sin;
sin.sin_port=htons(15777); //Connect to port 15777
sin.sin_addr.s_addr=inet_addr("127.0.0.1"); //Connect to localhost
sin.sin_family=AF_INET;
ioctlsocket(Szocket,FIONBIO,&iMode);
if(connect(kSock,(sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR){ //Check the condition
std::cout<<"Connect failed, error: "<<WSAGetLastError(); //Returns error code
WSACleanup(); //Cleanup the library
std::string lisquit;
std::cin>>lisquit;
}
std::cout<<"Connection successful!\n";
timeval tiz;
tiz.tv_sec = 1;
tiz.tv_usec = 0;
FD_SET OrigMC;
FD_SET PrxMC;
//while (true){
FD_ZERO(&OrigMC);
FD_ZERO(&PrxMC);
FD_SET(Szocket,&PrxMC);
FD_SET(kSock,&OrigMC);
cout<<"Loop started.\n";
int selecta = select(0,&PrxMC,NULL,NULL,&tiz);
cout<<"Has ready to recive: "<<selecta<<"\n";
//if(selecta == 1){
recv(Szocket,uua,sizeof(uua),0); //Recive from my proxy server
send(kSock,uua,sizeof(uua),0); //Send to the real one
cout<<"In: "<<uua<<"\n\n"; //Echo it
//}
int selectb = select(0,&OrigMC,NULL,NULL,&tiz);
cout<<"Has ready to recive: "<<selectb<<"\n";
if(selectb == 1){
recv(kSock, buf, sizeof(buf), 0); //Recive from the real server
send(Szocket,buf,sizeof(buf),0); //Send to the proxy server
cout<<"Out: "<<buf<<"\n\n"; //Echo what it just recived and sent
}
//No more sleep?
Sleep(50);
// Azjherben.org
//}
}