c++ connect() keeps returning WSATIMEDOUT over internet but not localy
For some reason, my chat application always gets WSATIMEDOUT when trying to connect to another person over开发者_C百科 the internet.
int len_ip = GetWindowTextLength(GetDlgItem(hWnd,ID_EDIT_IP));
char ipBuffer[16];
SendMessage(GetDlgItem(hWnd,ID_EDIT_IP),WM_GETTEXT,16,(LPARAM)ipBuffer);
long host_ip = inet_addr(ipBuffer);
int initializeConnection(long host_ip, HWND hWnd) {
// initialize winsock
WSADATA wdata;
int result = WSAStartup(MAKEWORD(2,2),&wdata);
if (result != 0) {
return 0;
}
// setup socket
tcp_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (tcp_sock == INVALID_SOCKET) {
return 0;
}
// setup socket address
SOCKADDR_IN tcp_sock_addr;
tcp_sock_addr.sin_family = AF_INET;
tcp_sock_addr.sin_port = SERVER_TCP_PORT;
tcp_sock_addr.sin_addr.s_addr = host_ip;
// connect to server
if (connect(tcp_sock,(SOCKADDR*)&tcp_sock_addr,sizeof(tcp_sock_addr)) == SOCKET_ERROR) {
return 0;
}
HRESULT hr = WSAGetLastError();
// set socket in asynchronous mode
if (WSAAsyncSelect(tcp_sock,hWnd,SOCKET_TCP, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE) == SOCKET_ERROR) {
return 0;
}
return 1;
}
For some reason it works perfectly fine on local network between computers, but totally screws up over the internet. WSATIMEDOUT is always returned (not connection refused, so its not a port problem). It makes me believe something is wrong with the IP but why on earth can it work on local addresses (like 192.168.2.4)
Any ideas?
Cheers
Firewalls and/or Nat-routers perhaps? You will need hole punching: http://en.wikipedia.org/wiki/Hole_punching
It could be a firewall configured to drop incoming requests instead of rejecting them. Sometimes this is called "stealth" mode.
精彩评论