为什么不输出响应?

时间:2018-12-01 19:10:55

标签: c++ sockets

我是套接字编程和c ++的新手。下面的代码构建良好,但是当我运行它时,它会提示我进入一个网站,并在cmd上进入一个网站后,不会输出响应消息。相反,它将加载几秒钟,然后出现“按任意键关闭”消息。我在做什么错??

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

int main()
{
    WSADATA wsaData;
    // Initialize Winsock
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    //Create a SOCKET for connecting to server
    SOCKET clientSocket = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);

    //prompts the user to enter a website.
    std::string webadd;
    std::cout << "Enter a website: \n";
    std::cin >> webadd;

    //finds the IP address of the website.
    addrinfo af;
    addrinfo* result;
    ZeroMemory(&af, sizeof(af));
    af.ai_family = AF_UNSPEC;
    af.ai_socktype = SOCK_STREAM;
    af.ai_protocol = IPPROTO_TCP;

    getaddrinfo(webadd.c_str(), "443", &af, &result);

    //  connects to this website.
    connect(clientSocket, result->ai_addr, result->ai_addrlen);

    //sends a valid html request to this website.
    std::string sendbuf = "GET / HTTP/1.1\nhost: " + webadd + "\n\n";
    send(clientSocket, sendbuf.c_str(), sendbuf.length(), 0);

    int iResult;
    char recvbuf[1024];
    // receive data
    iResult = recv(clientSocket, recvbuf, sizeof(recvbuf),0);
    if (iResult > 0)
        std::cout << "Responce from server:\n" << recvbuf << std::endl;
    else if(iResult == 0)
        std::cout << "Connection closed\n";
    else
        std::cout << "recv failed with error: " << WSAGetLastError() << std::endl;

    // close connection and cleanup
    closesocket(clientSocket);
    WSACleanup();   


system("pause");
return 0;

}

0 个答案:

没有答案