c++ connect() keeps returning WSATIMEDOUT over internet but not localy

Posted by KaiserJohaan on Stack Overflow See other posts from Stack Overflow or by KaiserJohaan
Published on 2011-01-03T23:48:42Z Indexed on 2011/01/03 23:53 UTC
Read the original article Hit count: 229

Filed under:
|
|
|
|

Hello,

For some reason, my chat application always gets WSATIMEDOUT when trying to connect to another person over 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

© Stack Overflow or respective owner

Related posts about c++

Related posts about winapi