我正在學習使用 C 進行套接字編程。我正在嘗試發出 HTTP 請求并獲得它的回應。
我將回應放入一個名為“response.txt”的檔案中。由于我不知道回應將持續多長時間,所以我將 recv() 放在一個 while 回圈中,將接收到的內容附加到“response.txt”,并在套接字接收到 0 個位元組時中斷回圈。
我的問題是我收到了 2 個回復。一個是“HTTP/1.1 200 OK”,另一個是“HTTP/1.1 400 Bad Request”。
我想知道為什么會這樣。是因為我的代碼中有一些不需要的錯誤,還是因為某些網路或協議設計?
這是與http請求相關的代碼部分。
// create socket
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *server = gethostbyname(www_ip); // www_ip is command line argument
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = * (unsigned long *) server->h_addr_list[0];
addr.sin_port = htons(80);
// connect
int connection_status = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));
// sending HTTP request
char test_msg[] = "GET /code/romeo.txt HTTP/1.1\r\nHost: www.py4inf.com\r\n\r\n";
int byte_sent;
byte_sent = send(sockfd, test_msg, sizeof(test_msg), 0);
// receiving HTTP response
char recv_data[1000];
int byte_recv;
FILE* fp = fopen("response.txt", "a");
while (1){
byte_recv = recv(sockfd, &recv_data, 1000, 0);
if (byte_recv == -1) {
exit(-1);
}
if (byte_recv == 0) {
break;
}
fputs(recv_data, fp);
}
fclose(fp);
// close connection
close(sockfd);
這是 response.txt 中的內容。
“誰已經病倒,悲痛欲絕”這行應該是請求檔案的最后一行。但在那之后有一個“HTTP/1.1 400 Bad Request”
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 167
Connection: keep-alive
Keep-Alive: timeout=15
Date: Sun, 27 Feb 2022 16:38:11 GMT
Server: Apache
Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT
ETag: "a7-526172f58b800"
Accept-Ranges: bytes
Cache-Control: max-age=604800, public
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: GET
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
HTTP/1.1 400 Bad Request
Server: nginx
Date: Sun, 27 Feb 2022 16:38:11 GMT
Content-Type: text/html
Content-Length: 150
Connection: close
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>
c
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: GET
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
uj5u.com熱心網友回復:
char test_msg[] = "GET /code/romeo.txt HTTP/1.1\r\nHost: www.py4inf.com\r\n\r\n"; int byte_sent; byte_sent = send(sockfd, test_msg, sizeof(test_msg), 0);
sizeof(test_msg)是請求的長度加一。這意味著它不僅會發送請求,還會發送\0字串末尾的 for。這將被視為下一個錯誤請求。
而不是sizeof(test_msg)使用strlen(test_msg)- 它給出了字串的大小而不是字串緩沖區。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434840.html
上一篇:無法寫入x64程式集中使用malloc/calloc請求的記憶體
下一篇:優化明顯任務
