套接字-在客户端使用INADDR_ANY [英] Sockets - Using INADDR_ANY on client side

查看:926
本文介绍了套接字-在客户端使用INADDR_ANY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了此博客文章描述了使用libev的TCP服务器客户端.服务器使用INADDR_ANY绑定到我熟悉的接口.但是,我也很惊讶在客户端代码中看到INADDR_ANY.客户端代码上的相关代码如下:

I recently ran into this blog post which describes a TCP server client using libev. The sever uses INADDR_ANY to bind to an interface which is something I'm familiar with. However, I was surprised to see INADDR_ANY in the client code as well. The relevant code on the client code is as follows:

// Create client socket
if( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
{
  perror("socket error");
  return -1;
}

bzero(&addr, sizeof(addr));

addr.sin_family = AF_INET;
addr.sin_port = htons(PORT_NO);
addr.sin_addr.s_addr = htonl(INADDR_ANY);

// Connect to server socket
if(connect(sd, (struct sockaddr *)&addr, sizeof addr) < 0)
{
  perror("Connect error");
  return -1;
}

特别是我对这一行感兴趣:

Specifically I'm interesed in the line:

addr.sin_addr.s_addr = htonl(INADDR_ANY);

在服务器端,我了解到INADDR_ANY会将端口绑定到所有可用接口,但是我不确定在客户端这有何意义.最后,客户端将需要在特定接口上进行连接.以前,我总是指定IP地址或使用INADDR_LOOPBACK.

On the server side I understand that INADDR_ANY will bind the port to all available interfaces, but I'm not sure how this makes sense on the client side. In the end, the client will need to connect on a particular interface. Previously I have always specified the IP address or used INADDR_LOOPBACK.

Linux IP手册页不显示关于在客户端上使用INADDR_ANY的信息.我确实找到了

The Linux IP man page doesn't talk about using INADDR_ANY on the client side. I did find another Stack Overflow post here which says that the OP should use INADDR_ANY on the client side, but gives no justification or explanation.

那么这到底在做什么?是否尝试所有接口,直到找到一个可用于连接的端口?这是什么顺序发生的?

So what is this actually doing? Is it trying all interfaces until it finds one where the port is available for connection? What order does this happen in?

感谢您的回答!

推荐答案

这是nos在评论中提供的答案.如果nos回来并将其发布为答案,我将nos标记为答案并删除该帖子.

This is the answer as provided by nos in a comment. If nos comes back and posts it as an answer, I will mark nos' post as the answer and delete this one.

INADDR_ANY通常定义为0.即IP地址0.0.0.0. RFC 1122表示这意味着此网络上的主机". linux IP 堆栈似乎只是将其路由到回送接口. (例如,尝试 ping 0.0.0.0甚至只是ping 0).我想说作者打错了字, 应该使用了INADDR_LOOPBACK.

INADDR_ANY is normally defined as 0. That is the IP address 0.0.0.0. RFC 1122 says that means "This host on this network". The linux IP stack seems to just route this to the loopback interface. (e.g. try ping 0.0.0.0 or even just ping 0). I'd say the author made a typo, and should have used INADDR_LOOPBACK.

这篇关于套接字-在客户端使用INADDR_ANY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆