Here is my code:

struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(80); char* ip = "151.101.129.69"; //ru.stackoverflow.com addr.sin_addr.s_addr = htonl(ip2int(ip)); int sockRequest = socket(AF_INET, SOCK_STREAM , 0); if(sockRequest == -1)exit(2); char* request = "GET HTTP/1.1\r\nHost: ru.stackoverflow.com\r\n\r\n"; printf("%s\r\n", request); write(sockRequest, request, strlen(request)); char buff[1024]; int count = read(sockRequest, buff, 1024); write(1, buff, count + 1); write(1, "\r\n", 1); close(sockRequest); 

Postman with this request

 GET HTTP/1.1 Host: ru.stackoverflow.com 

gives the html content of the site, and my program gives the error 400 "Bad request" .
What's wrong?

  • 3
    And who will write the way? GET / HTTP/1.1 . - Ainar-G
  • Two spaces are equivalent to / in my case. Those. so that so, the result is one - Belenot
  • one
    Is it possible to quote from the RFC, from which this equivalence follows? - Alexander Prokoshev
  • 2
    Try your hands through telnet. I have a Bad request on GET HTTP/1.1 , but on GET / HTTP/1.1 - HTTP/1.1 301 Moved Permanently ... Location: https://ru.stackoverflow.com/ , and in the response body - <h2>Object moved to <a href="https://ru.stackoverflow.com/">here</a>. </h2> <h2>Object moved to <a href="https://ru.stackoverflow.com/">here</a>. </h2> . Probably Postman correctly handles the https protocol forwarding. - avp pm
  • and yes, confused, you need to write url. But in this case, it gives an error 301, as written by @avp. What is the difference between the http and https connections (except for specifying the port 443 to the socket)? Or for this question it is better to create a separate question, and here indicate the correct answer @avp? - Belenot

2 answers 2

By standard , the path is required in the request. So that:

 char* request = "GET / HTTP/1.1\r\nHost: ru.stackoverflow.com\r\n\r\n"; 
  • Well, I do not even know whether to put you the correct answer or not. Yes, this resolves error 400, but error 301 remains. After all, the question was not to remove the error 400, but to understand how to make a request. In the comments to the question, Mr. @avp correctly wrote about the redirection to the https protocol, but I can not find the information on the Internet. - Belenot 5:56 pm
  • @Belenot If you are doing this for the sake of learning, I recommend searching the network for information about TLS / SSL connections on C. If you need for practical purposes, it is better to use libcurl instead of building crutches. - Ainar-G

Forgot to connect:

 connect(sockRequest,(struct sockaddr *)&addr,sizeof(addr)); 
  • one
    Then he would not receive a response from the server. - Sergey Gornostaev