gpt4 book ai didi

c - gethostbyname,连接到整个互联网?

转载 作者:行者123 更新时间:2023-11-30 14:26:00 26 4
gpt4 key购买 nike

我正在用 C 语言编写一个基本的代理服务器。

我正在使用firefox进行测试,并且我已经让服务器成功接收了浏览器的请求。

但现在我需要将它们发送到互联网以获取浏览器想要的页面,而我很犹豫。

这是我目前的连接代码。

我不确定端口 8080 是否正确,并且我不确定为“gethostbyname”添加什么。这就是我希望得到一些建议的部分。

  int sock = socket( PF_INET, SOCK_STREAM, 0 );

if ( sock < 0 )
{
perror( "socket() failed" );
return EXIT_FAILURE;
}

struct sockaddr_in server;
struct hostent * hp;

server.sin_family = PF_INET;
hp = gethostbyname( "localhost" );
if ( hp == NULL )
{
perror( "Unknown host" );
return EXIT_FAILURE;
}

bcopy( (char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length );
int port = 8080;
server.sin_port = htons( port );

if ( connect( sock, (struct sockaddr *)&server, sizeof( server ) ) < 0 )
{
perror( "connect() failed" );
return EXIT_FAILURE;
}

最佳答案

整个 gethostbyname,复制(哈 - 即使使用过于旧的 bcopy)...只需使用 getaddrinfo (为简洁起见,省略了广泛的错误检查):

int ret = getaddrinfo("localhost", "80" /* (or 8080, whichever applies) */, NULL, &res);
if (ret == 0) {
const struct addrinfo *r;
for (r = res; r != NULL || ret != 0; r = r->ai_next)
ret = connect(fd, res->ai_addr, res->ai_addrlen);
}
freeaddrinfo(res);

关于c - gethostbyname,连接到整个互联网?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9709529/

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