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

    int conn_s = socket(AF_INET, SOCK_STREAM, 0);
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;

    struct addrinfo *addr = (struct addrinfo *) calloc(1, sizeof(struct addrinfo));

    getaddrinfo("google.com", "80", &hints, &addr);

    connect(conn_s, addr->ai_addr, sizeof(struct sockaddr_in));

    char *http_request = "GET / HTTP/1.1\n\n";

    send(conn_s, http_request, strlen(http_request), 0);
    FILE *sockfile = (FILE *) fdopen(conn_s, "r");
    FILE *fp = fopen("/Users/leekaiwei/Desktop/results.html", "w+");
    int ch;

    while ((ch = fgetc(sockfile)) != EOF) {
        fprintf(fp, "%c", ch);
    }

    close(conn_s);
    fclose(fp);
    fclose(sockfile);
    free(addr);
    return 0;
}

while 循环永远不会结束。为什么是这样?我已经使用本地文件完成了此操作,并且工作正常。它也适用于 for 循环,只是 fgetc() 永远不会返回 EOF。

4

1 回答 1

3

HTTP/1.1默认为connection: keepalive,所以就像 simonc 所说,服务器实际上是在等待你发出下一个请求,并且会等到与服务器相关的超时。用于HTTP/1.0获取EOF.

FWIW:完成需要 245 秒。

于 2012-11-06T16:18:06.520 回答