   Port Forwarding
  I recently wrote a little chat program and I tried to connect it over the internet. I forwarded the server's port from my router and sent the client program to my friend. Unfortunately it didn't work, and I'm not sure what would be the problem. My chat program works fine locally and I'm pretty sure I set up the port forward right. Is there anything else I need to be aware of in order to connect over the internet? And could an error in my code keep my program from connecting over the internet, despite working locally?Thanks!ScottServer:#include <winsock2.h>#include <windows.h>#include <iostream>#include <string.h>#include <sstream>using namespace std;int port = 4444;WSADATA wsaData;SOCKET listenSocket = INVALID_SOCKET;sockaddr_in clientSockAddr[6];int clientSockSize;int* clientSock[6];int numClients = 0;const int buffer_length = 128;bool done = false;//Receive Messages From ClientsDWORD WINAPI receiveMessages(void* lp){ int *cs = (int*)lp; cout << "New connection made.\n"; while(!done){  int size;  char buffer[buffer_length];  memset(buffer, 0, buffer_length);  //Get Message  size = recv(*cs, buffer, buffer_length, 0);  if(size == 0)   break;  else if(size == SOCKET_ERROR){   cout << "socket error while receiving. Error: " << WSAGetLastError() << "\nThe connection may be recovered...\n";   break;  }else{   //Print Message   buffer[size] = '\0';   cout << buffer;  } } return 0;}//Send Messages to ClientsDWORD WINAPI sendMessages(void* lp){ //IM Send Loop while(1){  //Get Input  string s;  getline(cin, s);  //Exit?  if(s == "exit"){   done = true;   break;  }  //Append New Line  s += "\n";  //Send Message to All  for(int i = 1; i < numClients; i++){   if(*clientSock != INVALID_SOCKET){    if(send(*clientSock, s.c_str(), s.length(), 0) == SOCKET_ERROR && WSAGetLastError() != 10038 && WSAGetLastError() != 10054)cout << "socket error while sending. Error: " << WSAGetLastError();   }else    cout << "Not Connected, retry.\n";  } } return 0;}//Get New ClientsDWORD WINAPI listen(void* lp){ while(!done){  //Accept Connection  clientSock[numClients] = (int*)malloc(sizeof(int));  *clientSock[numClients] = accept(listenSocket, (SOCKADDR*) &clientSockAddr[numClients], &clientSockSize);  //Serve Client  if(*clientSock[numClients] != INVALID_SOCKET)   CreateThread(0, 0, &receiveMessages, (void*)clientSock[numClients], 0, 0);  numClients++; } return 0;}//Set Up Listenervoid runServer(){ sockaddr_in sockAddr = {0}; //Create cout << "Creating socket... "; if ((listenSocket = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)  cout << "could not create socket. Error: " << WSAGetLastError(); else cout <<"created.\n"; //Set up sockAddr cout << "Binding socket... "; sockAddr.sin_family = AF_INET; sockAddr.sin_port = htons(port); memset(&(sockAddr.sin_zero), 0, 8); sockAddr.sin_addr.S_un.S_addr = INADDR_ANY; //Bind if(bind(listenSocket, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR)  cout << "could not bind socket. Error: " << WSAGetLastError(); else cout <<"bound.\n"; //Listen cout << "Entering listen mode... "; if(listen(listenSocket, 10) == SOCKET_ERROR)  cout << "could not enter listen mode. Error: " << WSAGetLastError(); else cout <<"Listening.\n"; //Get Clients clientSockSize = sizeof(SOCKADDR); CreateThread(0, 0, &listen, NULL, 0, 0);}int main(void){ CreateThread(0, 0, &sendMessages, NULL, 0, 0); //Start Winsock cout << "Initializing winsock... "; if(WSAStartup(MAKEWORD(2, 2), &wsaData) == 0){  if(LOBYTE(wsaData.wVersion) >= 2 && HIBYTE(wsaData.wVersion) >= 2){   cout << "initialized.\n";   //Create, Bind, Listen, Accept Socket   runServer();  }else cout << "required version not supported! Error: " << WSAGetLastError(); }else cout << "Startup failed! Error: " << WSAGetLastError(); while(!done){} //Cleanup cout << "Cleaning up winsock... "; //Client Sockets for(int i = 0; i < numClients; i++){  closesocket(*clientSock);  free(clientSock); } //Server Socket if(listenSocket != INVALID_SOCKET)  closesocket(listenSocket); //Cleanup if(WSACleanup()!= 0){  cout << "cleanup failed! Error: " << WSAGetLastError(); }else cout << "done.\n"; return 0;}[color="#0000ff"][color="#0000ff"]Client:#include <winsock2.h>#include <windows.h>#include <iostream>#include <string.h>#include <sstream>using namespace std;int port = 4444;string name;WSADATA wsaData;int hsock;const int buffer_length = 128;bool done = false;//Send Messages to serverDWORD WINAPI sendMessages(void* lp){ //IM Send Loop while(1){  //Get Input  string s;  getline(cin, s);  //Exit?  if(s == "exit"){   done = true;   break;  }  //Append New Line  s += "\n";  //Send Message to All  if(hsock != INVALID_SOCKET){   if(send(hsock, s.c_str(), s.length(), 0) == SOCKET_ERROR && WSAGetLastError() != 10038 && WSAGetLastError() != 10054)    cout << "socket error while sending. Error: " << WSAGetLastError();  }else   cout << "Not Connected, retry.\n"; } return 0;}//Set Up Listenervoid runClient(){ //Set up sockAddr sockaddr_in sockAddr; sockAddr.sin_family = AF_INET; sockAddr.sin_port = htons(port); sockAddr.sin_addr.S_un.S_addr = inet_addr(name.c_str()); //Create cout << "Creating socket... "; if ((hsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)  cout << "could not create socket. Error: " << WSAGetLastError(); else cout <<"created.\n"; //Connect cout << "Connecting to server... "; if(connect(hsock, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR)  cout << "could not connect to server. Error: " << WSAGetLastError(); else cout <<"Connected.\n"; //Receive Messages if(hsock != INVALID_SOCKET){  while(!done){   int size;   char buffer[buffer_length];   //Get Message   size = recv(hsock, buffer, buffer_length, 0);   if(size == 0)    break;   else if(size == SOCKET_ERROR){    cout << "socket error while receiving. Error: " << WSAGetLastError() << "\nThe connection may be recovered...\n";    break;   }else{    //Print Message    buffer[size] = '\0';    cout << buffer;   }  } }}int main(void){ //Get IP cout << "Please enter the IP to connect to:\n"; string tempIP; getline(cin, name); cout << "\n"; //Send Messages CreateThread(0, 0, &sendMessages, NULL, 0, 0); //Start Winsock cout << "Initializing winsock... "; if(WSAStartup(MAKEWORD(2, 2), &wsaData) == 0){  if(LOBYTE(wsaData.wVersion) >= 2 && HIBYTE(wsaData.wVersion) >= 2){   cout << "initialized.\n";   //Create, Connect Socket   runClient();  }else cout << "required version not supported! Error: " << WSAGetLastError(); }else cout << "Startup failed! Error: " << WSAGetLastError(); //Cleanup cout << "Cleaning up winsock... "; //Server Sockets closesocket(hsock); //Cleanup if(WSACleanup()!= 0){  cout << "cleanup failed! Error: " << WSAGetLastError(); }else cout << "done.\n"; return 0;}
I recently wrote a little chat program and I tried to connect it over the internet. I forwarded the server's port from my router and sent the client program to my friend. Unfortunately it didn't work, and I'm not sure what would be the problem. What IP address did you enter on the external machine? It has to be the IP address of the firewall/router.Also, if you use Putty in RAW mode, and connect to your firewall IP/port, does it connect, or say that no connection can be established? Doing this will figure out whether the port forward is correct or not.   ;[quote name='swilkewitz' timestamp='1300829924' post='4789281']I recently wrote a little chat program and I tried to connect it over the internet. I forwarded the server's port from my router and sent the client program to my friend. Unfortunately it didn't work, and I'm not sure what would be the problem. What IP address did you enter on the external machine? It has to be the IP address of the firewall/router.Also, if you use Putty in RAW mode, and connect to your firewall IP/port, does it connect, or say that no connection can be established? Doing this will figure out whether the port forward is correct or not.[/quote]I have been using the IP that I got from whatismyip.com, which should be my external ip.Putty said that the connection was refused. Also, I have tried various free port checking services online and they come back positive only while my server is running, and my server even acknowledges the connection. So is there a reason why the port isn't visible? I'm pretty sure my router's firewall is disabled.   ;  So I redid my program so that the server and client are in the same executable. I also took out multithreading for multiple connections, but I still use it to send and receive simultaneously. Anyway it works better now, but it still won't connect through my router. I am pretty sure my port forwarding is working because my server can receive connections from port checkers online. So I'm still not sure why my program can't connect over the internet.Also, do you have any suggestions for improving my code? Are there alternative solutions that could replace anything that I'm using? I already fixed the while(1){} and got rid of as much multithreading as possible. I will also look into the select() method.//Simple Chat Program by Scott Wilkewitz#include <winsock2.h>#include <ws2tcpip.h>#include <windows.h>#include <iostream>#include <string.h>#include <sstream>using namespace std;//Connectionbool isHost = false;const int port = 4444; string host = "";//SocketsWSADATA wsaData;sockaddr_in sockAddr;int clientSocket, clientSockSize, hostSocket, externalSocket;sockaddr_in clientSockAddr;//Messagesconst int buffer_length = 128;bool done = false;//Methodsbool collectData();bool startWinsock();bool prepareSockets();DWORD WINAPI receiveMessages(void* lp);bool sendMessages();bool reinitiate();bool cleanSockets();int main(int argc, char *argv[]){ //Initiate Connection if(!collectData())  return 0; if(!startWinsock())  return -1; if(!prepareSockets()){  cleanSockets();  return -1; } //Send and Receive Messages CreateThread(0, 0, &receiveMessages, NULL, 0, 0); sendMessages(); //Close cleanSockets(); return 0;}bool collectData(){ //Get Role cout << "Host session? (y/n)\n"; getline(cin, host); cout << "\n"; if(host == "y")  isHost = true; else if(host == "n"){  //Get IP  cout << "Please enter the host's IP:\n";  getline(cin, host);  cout << "\n"; }else return false; return true;}bool startWinsock(){ cout << "Initializing winsock... "; //Start Winsock if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){  cout << "startup failed! Error: " << WSAGetLastError();  return false; } //Check Version if(LOBYTE(wsaData.wVersion) < 2 || HIBYTE(wsaData.wVersion) < 2){  cout << "required version not supported! Error: " << WSAGetLastError();  return false; } cout << "initialized.\n"; return true;}bool prepareSockets(){ //Set Address Info sockAddr.sin_family = AF_INET; sockAddr.sin_port = htons(port); memset(&(sockAddr.sin_zero), 0, 8); //Set Host IP if(isHost) sockAddr.sin_addr.S_un.S_addr = INADDR_ANY; else  sockAddr.sin_addr.S_un.S_addr = inet_addr(host.c_str()); //Create Socket cout << "Creating socket... "; if ((hostSocket = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET){  cout << "could not create socket. Error: " << WSAGetLastError();  return false; } cout << "created.\n"; if(isHost){  //Bind  cout << "Binding socket... ";  if(bind(hostSocket, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR){   cout << "could not bind socket. Error: " << WSAGetLastError();   return false;  }  cout << "bound.\n";  //Listen  cout << "Entering listen mode... ";  if(listen(hostSocket, 10) == SOCKET_ERROR){   cout << "could not enter listen mode. Error: " << WSAGetLastError();   return false;  }  cout <<"listening...\n";  //Accept  clientSockSize = sizeof(SOCKADDR);  externalSocket = accept(hostSocket, (SOCKADDR*) &clientSockAddr, &clientSockSize); }else{  //Connect  cout << "Connecting to host... ";  externalSocket = hostSocket;  if(connect(externalSocket, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR){   cout << "could not connect to host. Error: " << WSAGetLastError();   return false;  }  cout << "Connected.\n"; } //Check Validity if(externalSocket == INVALID_SOCKET){  cout << "\nError: Invalid socket.\n";  return false; } return true;}DWORD WINAPI receiveMessages(void* lp){ //Connection loop while(!done){  cout << "\nNew connection made.\n\n";  //Message loop  while(!done){   int size;   char buffer[buffer_length];   memset(buffer, 0, buffer_length);   //Get Message   size = recv(externalSocket, buffer, buffer_length, 0);   //D/C   if(size == 0){    cout << "\nDisconnected.\n\n";    break;   }   //Error Processing   else if(size == SOCKET_ERROR){    int error;    error = WSAGetLastError();    //D/C    if(error == WSAECONNRESET){cout << "\nDisconnected.\n\n";break;    }   //Print Message   }else{    buffer[size] = '\0';    cout << buffer;   }  }  //Restart Connection  if(isHost) reinitiate();  else    break; } return 0;}bool sendMessages(){ //IM Send Loop cout << "\nReady to send Messages! Press enter to send, type exit to disconnect.\n\n"; while(!done){  //Get Input  string s;  getline(cin, s);  //Exit?  if(s == "exit"){   done = true;   cout << "\nDisconnecting!\n\n";   return true;  }  //Append New Line  s += "\n";  //Send Message  int size;  size = send(externalSocket, s.c_str(), s.length(), 0);  //Error Processing  if(size == SOCKET_ERROR){   int error;   error = WSAGetLastError();   //D/C   if(error == WSAECONNRESET){    cout << "\nDisconnected, message was not sent!\n\n";    return true;   }  } } return true;}bool reinitiate(){ cout << "\nReinitiating connection... "; externalSocket = accept(hostSocket, (SOCKADDR*) &clientSockAddr, &clientSockSize); cout << "connected.\n"; return 0;}bool cleanSockets(){ //Close Sockets closesocket(clientSocket); closesocket(hostSocket); closesocket(externalSocket); WSACleanup(); return true;};  The first thing you need to do is determine where the problem actually is.If you run the server and port checkers can connect, everything seems to be fine on your side.If you run the server and a friend cannot connect, there could be something wrong with your client or their network (PC's AV, firewall, etc...)If you run the server and cannot connect from inside your own network, it's a server bug or LAN issue (if you have multiple NICs or the LAN address the PC is using is not really part of the LAN due to a misconfiguration).Try to find another program to test this stuff with. Perhaps a putty server or light weight web server or anything that you find. If you can get a well known program to work, chances are there is something with the code itself. If the known programs do not work, then you know it's settings on your PC/Router, or quite possibly with the ISP (unlikely, but try changing port #s in that case).   ;  Putty can't connect through my router, my friends can't connect, but online port checkers can connect.Everything works fine locally, but I just can't host anything behind my router besides those port checkers... this is confusing.I haven't had any of my friends try to host it, do you think I should do that?I wouldn't be surprised if the problem was with my router, apparently it is infamous.   ;Putty can't connect through my router, my friends can't connect, but online port checkers can connect.Putty from where? From your computer? Some routers don't support "hairpin" NAT, where you try to connect to the external port/address from the inside.   ;[quote name='swilkewitz' timestamp='1302383673' post='4796480']Putty can't connect through my router, my friends can't connect, but online port checkers can connect.Putty from where? From your computer? Some routers don't support "hairpin" NAT, where you try to connect to the external port/address from the inside.[/quote]Oh, I didn't know that. I will try connecting from outside then, I'll let you know how it works soon.   ;  It worked! I just had to let the server run behind my router and connect from outside. So the problem was the hairpin connection.Thanks!   