gpt4 book ai didi

c - 尝试下载流时,getaddrinfo()失败

转载 作者:行者123 更新时间:2023-12-03 11:51:35 25 4
gpt4 key购买 nike

我正在尝试使用套接字从实时流下载几秒钟。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> /* close() */
#include <sys/socket.h>
#include <netdb.h>

int main(void)
{
int sock;
char host[] = "http://141.138.89.176/fun-1-44-128";
char port[] = "80";
struct addrinfo hints, *res;
char message[] = "GET / HTTP/1.1\nHost: http://141.138.89.176/fun-1-44-128";
unsigned int i;
char buf[1024];
int bytes_read;
int status;

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
status = getaddrinfo(host, port, &hints, &res);
if (status != 0) {
perror("getaddrinfo");
return 1;
}
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock == -1) {
perror("socket");
return 1;
}
status = connect(sock, res->ai_addr, res->ai_addrlen);
if (status == -1) {
perror("connect");
return 1;
}
freeaddrinfo(res);
send(sock, message, strlen(message), 0);

do {
bytes_read = recv(sock, buf, 1024, 0);
if (bytes_read == -1) {
perror("recv");
}
else {
printf("%.*s", bytes_read, buf);
}
} while (bytes_read > 0);

close(sock);

return 0;
}

代码会编译,但是在运行时, getaddrinfo()失败。我认为这意味着找不到主机。
这是我的网址: http://141.138.89.176/fun-1-44-128
它可以在我的浏览器中工作,所以我不知道发生了什么。有人可以阐明这个问题吗?

最佳答案

我在您的环境上测试了您的代码,它可以正常工作,因此您的代码肯定可以。我建议检查您的编译器,也许重新安装它。
编辑:好的,我想我发现了问题。主机只能是ip地址,而不是完整链接。
(还为getaddrinfo中的错误报告添加了修复程序)

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> /* close() */
#include <sys/socket.h>
#include <netdb.h>

int main(void)
{
int sock;
char host[] = "141.138.89.176";
char port[] = "80";
struct addrinfo hints, *res;
char message[] = "GET / HTTP/1.1\nHost: 141.138.89.176/fun-1-44-128";
unsigned int i;
char buf[1024];
int bytes_read;
int status;

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
status = getaddrinfo(host, port, &hints, &res);
if (status != 0) {
printf("Code: %d\n", status);
printf("Message: %s\n", gai_strerror(status));
return 1;
}
...

关于c - 尝试下载流时,getaddrinfo()失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64803574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com