我完全不熟悉網絡編程。所以,我的工作是通過這樣的插座上的一個程序,並嘗試讀取HTML內容(我認爲這是在HTML,有人糾正我在這個):C recv()不在緩衝區中讀取
GET infolab.stanford.edu/~ullman/focs.html HTTP/1.1\r\n
Host: www.google.com\r\n
\r\n
infolab.stanford.edu/~ullman/focs.html
是網站我正在閱讀。
因此,我將那條GET消息存儲在一個字符串中,然後使用send()方法將請求發送到服務器。我檢查了errno,它返回Success
。
然後,我使用recv()來讀取內容並將其存儲在緩衝區中。我做了一些搜索,發現緩衝[6000]就像一個標準。
但是,我的程序需要永遠運行recv()。 errno返回Success
,但是當我嘗試打印緩衝區時,它只是一個空行。
int open_clientfd(char *hostname, int port)
{
int clientfd;
struct hostent *hp;
struct sockaddr_in serveraddr;
if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1; /* Check errno for cause of error */
/* Fill in the server's IP address and port */
if ((hp = gethostbyname(hostname)) == NULL)
return -2; /* Check h_errno for cause of error */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)hp->h_addr_list[0],
(char
*)&serveraddr.sin_addr.s_addr,
hp->h_length);
serveraddr.sin_port = htons(port);
/* Establish a connection with
* the server */
if (connect(clientfd, (SA *)
&serveraddr,
sizeof(serveraddr)) < 0)
return -1;
return clientfd;
}
void sendRequest(int clientfd, char request[128]) {
char buffer[6000];
int byteSent, byteRead;
// send request
byteSent = send(clientfd, request, sizeof(request), 0);
fprintf(stderr, "%s\n", strerror(errno));
// read
byteRead = recv(clientfd, buffer, sizeof(buffer), 0);
fprintf(stderr, "%s\n", strerror(errno));
fprintf(stdout, "%s\n", buffer);
}
int main(int argc, char **argv) {
int clientfd, port;
char *host, *fileURL;
rio_t rio;
host = argv[1];
fileURL = argv[2];
port = atoi(argv[3]);
clientfd = open_clientfd(host, port);
// set up request string
char request[128];
// ....
// now request stores the string above
sendRequest(clientfd, request);
return 0;
}
通常嫌疑犯:治療緩衝區作爲空終止字符數組時,不能保證如此。未能正確處理recv()返回的結果。 –
對於其中一個,'sendRequest'中的'send'調用中的'sizeof(request)'並不是按照您的想法進行的。當請求變量作爲參數傳遞時,request變量是一個通過轉換的指針,而不是來自調用者的數組,因此sizeof會正確地給出你所要求的:指針的大小。還有次要的,但它仍然不應該發生,沒有'Open_clientfd',但有'open_clientfd'。 – WhozCraig
..如果您正在考慮針對@WhozCraig評論達成strlen(),請再考慮一次。將希望發送的字節數作爲單獨的參數傳遞。 –