简体   繁体   English

WinSock无法连接

[英]WinSock can not connect

I've just started to learn WinSock. 我刚刚开始学习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. 我从阅读本文开始: https : //msdn.microsoft.com/zh-cn/library/windows/desktop/bb530750(v=vs.85) .aspx我做了写的事情。

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 我的代码在这里: http : //pastebin.com/0THqWKXv

Could you tell me what did I wrong? 你能告诉我我错了吗? How to repair my code? 如何修复我的代码?

PS. PS。 The IP adress is to google.pl IP地址是google.pl

PS2. 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);

}

You should call getaddrinfo() to resolve the address before calling connect() : 您应先调用getaddrinfo()来解析地址,然后再调用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);

I've changed addres to "google.com" and port to "80" and it works. 我已将addres更改为“ google.com”,并将端口更改为“ 80”,并且可以使用。 Thanks a lot! 非常感谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM