gpt4 book ai didi

bind() 套接字可以连接到远程地址吗?

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:00 27 4
gpt4 key购买 nike

通过下面的C代码快照,我明白了,bind()调用绑定(bind)到listfd的地址,是本地机器的逻辑地址服务器程序正在运行。随后,服务器监听同一台机器的 listfd 套接字。

struct sockaddr_in serv_addr; 
listfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(8000);
retval = bind(listfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listfd)

我在 coursera 学习了---bind() 调用还允许您将套接字绑定(bind)到远程地址和端口。

enter image description here我想了解这一点。

我的意思是, listfd = socket(AF_INET, SOCK_STREAM, 0);从运行此程序的程序进程(本地计算机)提供文件描述符。

我的问题:

如果 bind() 调用将此本地套接字 listfd 绑定(bind)到远程地址而不是 INADDR_ANY,那么实际上是哪台机器在监听?因为 listfd 是运行此程序的本地机器的本地进程文件描述符表中的一个条目,并且此套接字 listfd 正在绑定(bind)到远程机器 IP 地址?我该如何解释?这是如何工作的?

最佳答案

您不能bind() 到远程地址,至少不能在AF_INET 系列中。根据man page of bind ,你会得到一个EADDRNOTAVAIL错误,说你想绑定(bind)的地址不是本地的。

编辑:bind() 可能 适用于远程地址,但它肯定不适用于 AF_INET 系列。请注意,不止于此。可能有一些确实支持绑定(bind)到远程地址的系列,可能是一些集群协议(protocol)。即使没有,bind() 也可以在这些理论上 上工作,以防某些协议(protocol)出现在这完全有意义的地方。

编辑 2:作为 thuovila指出,实际上有一种情况可以在 AF_INET 中绑定(bind)远程地址。也就是说,在绑定(bind)之前设置 IP_TRANSPARENT 套接字选项。 The man page of ip(7)告诉我们:

   IP_TRANSPARENT (since Linux 2.6.24)
Setting this boolean option enables transparent proxying on
this socket. This socket option allows the calling
application to bind to a nonlocal IP address and operate both
as a client and a server with the foreign address as the local
endpoint. NOTE: this requires that routing be set up in a way
that packets going to the foreign address are routed through
the TProxy box (i.e., the system hosting the application that
employs the IP_TRANSPARENT socket option). Enabling this
socket option requires superuser privileges (the CAP_NET_ADMIN
capability).

TProxy redirection with the iptables TPROXY target also
requires that this option be set on the redirected socket.

因此,通过大量额外工作,您可以构建一个 transparent proxy通过将本地和远程套接字与该套接字选项集绑定(bind)在一起(如果我理解正确的话)。

关于bind() 套接字可以连接到远程地址吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111929/

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