0
votes

I've just started to learn WinSock. I started by reading this article: https://msdn.microsoft.com/en-us/library/windows/desktop/bb530750(v=vs.85).aspx And i did what I was wrote to do.

But I can not connect, every time I run this program i got same error:

Connection timed out. A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.

My code is here: http://pastebin.com/0THqWKXv

Could you tell me what did I wrong? How to repair my code?

PS. The IP adress is to google.pl

PS2. Actual code responsible for connection:

iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
while (iResult == SOCKET_ERROR){
    cout << "Blad ustanowienia polaczenia:\t" << WSAGetLastError() << endl;
    ptr = ptr->ai_next;
    iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);

}
2
Is there anything listening on the other side?David Schwartz
i hope that google is listening, em I wrong :D ?user4593532
for example i would like to download index.html from some wwwuser4593532
What is port? As I see from your source it's 27015 which is "standard" only for CS yet google still can't play CS ;-)Matt
@Piwniczne Why would Google be listening on port 27015?David Schwartz

2 Answers

0
votes

You should call getaddrinfo() to resolve the address before calling connect():

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(addr, nPort, &hints, &result);
    if ( iResult != 0 ) 
    {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) 
    {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) 
        {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) 
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);
0
votes

I've changed addres to "google.com" and port to "80" and it works. Thanks a lot!