【问题标题】:tcpclient - web client to get content in ctcpclient - 在 c 中获取内容的 Web 客户端
【发布时间】:2016-03-10 04:51:45
【问题描述】:

这是我必须从网站下载内容的代码,比如 wiki

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
void error(char *msg)
{
    fprintf(stderr, "%s: %s\n", msg, strerror(errno));
    exit(1);
}

int main(int argc, char *argv[])
{
    int d_sock;
    char buf[255];
    char rec[256];
    int bytesRcvd;
    int c, result;
    struct addrinfo *res;
    struct addrinfo hints;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    // get ip from list of domains and puts it onto heap called naming resource
    getaddrinfo("en.wikipedia.org", "80", &hints, &res);

    /*Creating socket */
    d_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (d_sock == -1)
        error("Can't open socket");

    /*Connecting socket */
    c = connect(d_sock, res->ai_addr, res->ai_addrlen);
    freeaddrinfo(res);
    if (c == -1)
        error("Can't connect to socket");

    /* Sending GET */
    sprintf(buf, "GET /wiki/%s http/1.1\r\n", argv[1]);
    result = send(d_sock, buf, strlen(buf), 0);
    if (result == -1)
        fprintf(stderr, "%s: %s\n", "Error talking to the server",
    strerror(errno));

    /* Sending Host and blank line */
    memset(buf, 0, 255);
    strcpy(buf, "Host: en.wikipedia.org\r\n\r\n");
    result = send(d_sock, buf, strlen(buf), 0);
    if (result == -1)
        fprintf(stderr, "%s: %s\n", "Error talking to the server",
    strerror(errno));

    /*Receiving the page information */
    bytesRcvd = recv(d_sock, rec, 255, 0);
    while (bytesRcvd) {
        if (bytesRcvd == -1)
            error("Can't read from server");
        rec[bytesRcvd] = '\0';
        printf("%s", rec);
        bytesRcvd = recv(d_sock, rec, 255, 0);
    }

    /*Closing socket */
    close(d_sock);
    return 0;
}

这里的问题是输出

HTTP/1.1 301 TLS 重定向
服务器:清漆
位置:https://en.wikipedia.org/wiki/apples
内容长度:0
接受范围:字节
日期:2015 年 12 月 5 日星期六 06:46:13 GMT
...

发生了什么,为什么会被重定向?我的课程使用 head first c book,我什至运行了示例,它也被重定向,但他们的 sn-ps 显示它成功获取了内容

【问题讨论】:

    标签: c redirect tcp tcpclient


    【解决方案1】:

    wikipedia 似乎现在将所有 http 请求重定向到 https,这就是为什么你得到这个 http 重定向,也许你应该考虑在另一个仍然使用 http 的网站上尝试你的代码(例如 stackoverflow)

    【讨论】:

    • 没有办法获取 https 吗?我尝试更改 sprintf(buf, "GET /wiki/%s http/1.1\r\n", argv[1]);以 https 为例
    • 为了使用 ssl,您必须包含一个实际执行加密的库(例如 openssl),我认为这超出了您的课程范围,这就是为什么我建议您切换到另一个网站的原因。跨度>
    • 啊好吧,这可以理解。谢谢你的帮助!
    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    相关资源
    最近更新 更多