WinSock无法连接

WinSock can not connect

本文关键字:连接 WinSock      更新时间:2023-10-16

我刚刚开始学习WinSock。我从阅读这篇文章开始:https://msdn.microsoft.com/en-us/library/windows/desktop/bb530750(v=vs.85).aspx我做了我被要求做的事。

但我无法连接,每次我运行这个程序时,我都会遇到同样的错误:

连接超时。连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为所连接的主机没有响应。

我的代码在这里:http://pastebin.com/0THqWKXv

你能告诉我我做错了什么吗?如何修复我的代码?

PS。IP地址是谷歌.pl

PS2。负责连接的实际代码:

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);
}

在调用connect():之前,您应该调用getaddrinfo()来解析地址

    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: %dn", 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: %ldn", 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);

我把地址改为"google.com",把端口改为"80",它就可以工作了。非常感谢!