1

我正在尝试编写一个获取 HTML 的 TCP 客户端。该程序将接受用户的网站并打印出内容。现在我的代码只取回一个 HTML 说错误 408 请求超时错误页面。问题出在哪里?

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



int main(int argc, char* argv[])
{
    char *domain = argv[1];
    char *path = strchr(domain, '/');
    *path++ = '\0';
    //printf("host: %s; path: %s\n", domain, path);

    int sock, bytes_recieved;  
    char send_data[1024],recv_data[9999];
    struct sockaddr_in server_addr;
    struct hostent *he;

    he = gethostbyname(domain);
    if (he == NULL){
       herror("gethostbyname");
       exit(1);
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, 0))== -1){
       perror("Socket");
       exit(1);
    }
    server_addr.sin_family = AF_INET;     
    server_addr.sin_port = htons(80);
    server_addr.sin_addr = *((struct in_addr *)he->h_addr);
    bzero(&(server_addr.sin_zero),8); 
    if (connect(sock, (struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1){
       perror("Connect");
       exit(1); 
    }

   snprintf(send_data, sizeof(send_data), "GET /%s HTTP/1.1\r\n Host: %s\r\n \r\n \r\n", path, domain);
   //printf("%s\n", send_data);
   send(sock, send_data, strlen(send_data), 0); 
   printf("Data sended.\n");  
   bytes_recieved = recv(sock, recv_data, 9999, 0);
   recv_data[bytes_recieved] = '\0';
   close(sock);
   printf("Data reveieved.\n");
   printf("%s\n", recv_data);


return 0;
} 

例如,现在如果我正在尝试运行 ./client www.facebook.com 它会返回一个 HTML 页面说发生错误

4

1 回答 1

1

检查您的 HTTP Get 请求,它应该是

GET /%s HTTP/1.1\r\n主机: %s\r\n\r\n

于 2013-10-14T20:12:18.840 回答