我努力讓自己在80端口的連接和本地主機發送一個簡單的HTTP GET請求,同時我跑Wireshark的,看看標題。這是我的代碼:C:發送HTTP GET請求在linux
#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));
}
但是,當我編譯它並運行它給了我很多erros。 here is the image of errros。發送此錯誤後,我將發送功能更改爲
send(sockfd,「GET/HTTP/1.1 \ r \ n Host:localhost \ r \ n \ r \ n」,strlen(「GET/HTTP/1.1 \ n主機:localhost \ r \ n \ r \ n「)
編譯OK,但wireshark顯示我HTTP/1.0 400 BAD REQUEST(text/html)所以我沒有幾個問題
1)什麼是我用過的發送函數之間的區別?我的意思是,真的很要緊,如果我送
GET/HTTP/1.1 \ r \ n主機:本地主機\ r \ n \ r \ n
或
GET/HTTP/1.1 \ r \ n 主機:本地主機\ r \ñ 連接:保持活着\ r \ n 緩存控制:最大年齡= 0 \ r \ n 接受:text/html的,應用/ XHTML + xml的,應用/ XML; q = 0.9,圖像/ WEBP,; q = 0.8 \ r \ n 的User-Agent:Mozilla的/ 5.0(X11; Linux的i686的)爲AppleWebKit/537.36(KHTML,例如Gecko)鉻/ 40.0.2214.91 Safari瀏覽器/ 537.36 \ r \ n 接受編碼: gzip的,放氣,SDCH \ r \ n 接受語言:EN-US,EN; q = 0.8 \ r \ n \ r \ n
2)如何配置發送功能來米ake正確的HTTP GET請求?
希望你能幫上忙。謝謝。
現在Wireshark的讓我 「GET/HTTP/1.1延續或非HTTP流量」 – Ojs
哦,我是用雙\ r \ n的主機。我的錯。謝謝:)你能回答第一個問題嗎? – Ojs
@Ojs很難理解這是一個問題。基本上,我只是說你應該閱讀HTTP規範並理解每個頭文件的作用。 –