What is the purpose and result of using INADDR_ANY?

无人久伴 提交于 2021-02-19 01:26:10

问题


In Python when we want to make a script that listens for multicast traffic we set the IP_ADD_MEMBERSHIP option of the socket with a value that consists of the multicast group address and the address of a local interface on which it will listen for the group's traffic.

Many examples on the Internet pass to IP_ADD_MEMBERSHIP the INADDR_ANY wildcard address as the local interface, and some of them state that this will make the socket to listen on all interfaces for multicast packets. However the Linux ip(7) man page states that when using INADDR_ANY

"an appropriate interface is chosen by the system"

and the freebsd man page says that it will choose the "default interface".

So either some answers online are wrong, or there's something that I'm missing here. I believe there's a confusion with INADDR_ANY when used as a parameter in IP_ADD_MEMBERSHIP, and INADDR_ANY when used as a parameter in bind() (represented by an empty string) but I'm not really sure. Can someone please clarify what is happening with INADDR_ANY or 0.0.0.0 when used in IP_ADD_MEMBERSHIP (i.e. it chooses the default interface or all interfaces) and if it behaves differently when used with bind?


回答1:


When INADDR_ANY is given as the address in a bind call, this causes the socket to listen on the given port for any network interface.

After calling bind in this way, you'll see an entry like this in the output of the netstat command:

udp        0      0 0.0.0.0:46162           0.0.0.0:*  

This is a UDP socket that was bound to INADDR_ANY with port 46162.

When used as the interface address when setting the IP_ADD_MEMBERSHIP option, INADDR_ANY indicates that the OS will chose an interface to join the given multicast group on, i.e. the "default" network interface.

It does not mean that it will join the group on all interfaces. To do that, you would need to itereate over all network interfaces and set the IP_ADD_MEMBERSHIP option on each one.

I've worked with Linux, Solaris, FreeBSD, and Windows, and none of them joins a multicast group on all interfaces when using INADDR_ANY.



来源:https://stackoverflow.com/questions/46066244/what-is-the-purpose-and-result-of-using-inaddr-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!