C: 在 linux 发送 http get 请求

C: Sending http get request in linux

我正在尝试在端口 80 上建立连接本地主机并发送一个简单的 http get 请求,同时我 运行 wireshark 并查看 headers。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>


int main(int argc, char *argv[])
{

  int yes = 1;
 char buffer[1024];
 int newsockfd, portno, recv_length, sockfd;
 socklen_t clilen;
 struct sockaddr_in serv_addr, cli_addr;
 ssize_t number;
 if (sockfd < 0) 
    error("ERROR opening socket");
 bzero((char *) &serv_addr, sizeof(serv_addr));


  sockfd = socket(AF_INET, SOCK_STREAM, 0);

 serv_addr.sin_family = AF_INET;
 serv_addr.sin_addr.s_addr = 0;
 serv_addr.sin_port = htons(80);




 connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr));


 if(send(sockfd, 


 "GET / HTTP/1.1\r\n
 Host: localhost\r\n
 Connection: Keep-alive\r\n
 Cache-Control: max-age=0\r\n
 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,;q=0.8\r\n
 User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36\r\n
 Accept-Encoding: gzip, deflate, sdch\r\n
 Accept-Language: en-US,en;q=0.8\r\n\r\n", 

 strlen("GET / HTTP/1.1\r\n
 Host: localhost\r\n
 Connection: Keep-alive\r\n
 Cache-Control: max-age=0\r\n
 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,;q=0.8\r\n
 User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36\r\n
 Accept-Encoding: gzip, deflate, sdch\r\n
 Accept-Language: en-US,en;q=0.8\r\n\r\n"),

 0) > 0)

 {
    printf("GET send from %d\n", sockfd);
 }
 else
 {
    printf("Problem in send %s\n", strerror(errno));
 }

但是当我编译它时 运行 它给了我很多错误。 here is the image of errros。在这个错误之后我将发送函数更改为this
send(sockfd, "GET / HTTP/1.1\r\n Host: localhost\r\n\r\n", strlen("GET / HTTP/1.1\r\n Host: localhost\r\n\r\n")
编译去了好的,但是 wireshark 显示 HTTP/1.0 400 BAD REQUEST (text/html) 所以我有几个问题。
1)我使用的发送功能有什么区别?我的意思是如果我发送
GET / HTTP/1.1\r\n 主机:localhost\r\n\r\n
或者
获取/HTTP/1.1\r\n 主持人:localhost\r\n 连接:Keep-alive\r\n Cache-Control: max-age=0\r\n 接受:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,;q=0.8\r\n User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537 .36\r\n Accept-Encoding: gzip, deflate, sdch\r\n Accept-Language: en-US,en;q=0.8\r\n\r\n
2)如何配置send函数来发出正确的HTTP GET请求?
希望对您有所帮助。谢谢

您的字符串中有文字换行符!您需要关闭并重新打开每行的报价。例如:

if(send(sockfd, 
 "GET / HTTP/1.1\r\n"
 "Host: localhost\r\n"
 "Connection: Keep-alive\r\n"
 "Cache-Control: max-age=0\r\n"
 ...