#include "iostream" #include "unistd.h" #include "netinet/in.h" #include "sys/types.h" #include "sys/socket.h" #include "fcntl.h" #include "tools.h"//мой файл. там strlen() и ip2int() using namespace std; int main(int argc, char** argv){ struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = htonl(ip2int(192,168,0,1)); int sockfd = socket(AF_INET, SOCK_STREAM, 0); connect(sockfd,(struct sockaddr*) &addr, sizeof(addr); char result[1024]; char request_buffer[] = "GET / HTTP/1.1\r\n\r\n";//Это исправлено for(int i = 0; i < 20; i++){ write(sockfd,request_buffer,strlen(request_buffer)); } read(sockfd, result, 1024); cout << result << endl; close(sockfd); return 0; } 

The body comes if you send requests several times. From the first time only headers come with an empty body.

    1 answer 1

    Send a new line twice: "GET / HTTP/1.1\r\n\r\n"

    The fact is that according to the HTTP 1.1 specification, the end of the request is \ r \ n after the empty string, that is, \ r \ n \ r \ n. This is done to be able to send request headers. For example:

     (request) GET / HTTP/1.1 Host: example.com (response) HTTP/1.1 200 OK Server: server version Date: date ... <HTML> ... 

    Try a telnet on the 80th port - it will become quite clear.

     #include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> int main(int argc, char** argv){ struct sockaddr_in addr; int status; status = 0; addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = inet_addr ("127.0.0.1"); int sockfd = socket(AF_INET, SOCK_STREAM, 0); connect(sockfd, (struct sockaddr*) &addr, sizeof(addr)); char result[1025]; char request_buffer[] = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; write(sockfd,request_buffer,strlen(request_buffer)); while (status = read (sockfd, result, 1024)) { printf ("=============== READ STATUS %d =============\n", status); printf ("%s\n", result); memset (&result, 0, sizeof (result)); } close(sockfd); return 0; } 

    I would not drag all the plus weight for cout alone.

    • Thank you, everything works in telnet, but the only thing that has changed in the program is that the error 408 has disappeared. The body still comes only after repeated requests - Belenot
    • one
      But show the fully up-to-date code together with the connection setup (the address is not necessary), otherwise I’m looking at sending the request in a loop and don’t really understand what we are talking about :) - Alexander Prokoshev
    • Fully added code - Belenot
    • one
      I corrected myself a bit (I still had to think out the functions). Works. - Alexander Prokoshev
    • one
      Not. Read the man read and see what errno is set to when it returns -1. But here I am no longer an assistant. - Alexander Prokoshev