使用低级C ++网络库发送GET请求时,网站没有响应

时间:2020-09-30 15:32:31

标签: c++ c linux http networking

我正在尝试创建一个程序,该程序使用c ++低级网络从网站下载数据。 这是代码:

#include <iostream>
#include <string>

#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <arpa/inet.h>



int status, sock;
struct addrinfo hints;
struct addrinfo *servinfo;
int main(int argc, char** argv){
  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  int MAXDATASIZE = 100;
  char request[] = "GET /robots.txt HTTP/1.1\n";
  char buf[MAXDATASIZE];
  if((status = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0){
    std::cout << "getaddrinfo: " << gai_strerror(status) << "\n";
    return 2;
  }
  if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
    std::cout << "Error creating socket\n";
    return 2;
  }
  if(connect(sock, servinfo->ai_addr, servinfo->ai_addrlen) == -1){
    std::cout << "Error connecting to host " << argv[1] << " at port " << argv[2] << "\n";
    return 2;
  }
  if((send(sock, request,strlen(request), 0)) == -1){
     std::cout << "Error communicating with website\n";
     return 2;
  }
  if(recv(sock, buf, MAXDATASIZE, 0) == -1){
     std::cout << "Error recciving data from " << argv[1] << " at port " << argv[2] << "\n";
  }
  std::cout << buf << std::endl;
  close(sock);

  freeaddrinfo(servinfo);
}

当我尝试使用www.google.com作为主机并使用80作为端口连接到google时,它挂在recv()调用上。要测试请求是否是问题,我使用telnet连接到google具有相同的请求,并且有效。我还尝试将netcat绑定到计算机上的端口,然后使用我的程序连接到该端口。该请求已正确发送到netcat,当我返回测试消息时,我的程序将其接收到。

有人知道为什么Google不发送数据吗?

如果使用Fedora 32,我会使用

1 个答案:

答案 0 :(得分:2)

您的软件未挂起。而是,服务器正在等待客户端已完成发送标头的指示,该指示由发送空行指示。在客户端发送空白行之前,服务器无法响应。

将您的请求更改为:

char request[] = "GET /robots.txt HTTP/1.1\r\n\r\n";