简体   繁体   English

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

[英]Website not responding when sending a GET request using low level c++ networking libraries

I am trying to create a program that downloads data from websites using c++ low level networking.我正在尝试创建一个使用 C++ 低级网络从网站下载数据的程序。 Here is the code:这是代码:

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

When I try to connect to google, using www.google.com as the host and 80 as the port, it hangs at the recv() call.To test whether the request was the problem, I connected to google using telnet with the same request, and it worked.当我尝试连接到谷歌时,使用www.google.com作为主机和 80 作为端口,它挂在 recv() 调用处。为了测试请求是否是问题,我使用 telnet 连接到谷歌请求,它奏效了。 I also tried binding netcat to a port on my computer, and then connected to that port using my program.我还尝试将 netcat 绑定到我计算机上的一个端口,然后使用我的程序连接到该端口。 The request was sent properly to netcat, and when I responded with a test message, my program reccived it.请求被正确发送到 netcat,当我用测试消息响应时,我的程序收到了它。

Does anyone know why google isn't sending the data?有谁知道为什么谷歌不发送数据?

I'm using fedora 32, if that might help我正在使用 Fedora 32,如果这可能有帮助的话

Your software is not hanging.您的软件没有挂起。 Rather, the server is waiting for an indication that the client has finished sending the headers, which is indicated by sending an empty line.相反,服务器正在等待客户端已完成发送标头的指示,这通过发送空行来指示。 Until the client sends the blank line, the server cannot respond.在客户端发送空行之前,服务器无法响应。

Change your request to:将您的请求更改为:

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

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

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