英文:
Get IP address of Interface for a UDP socket when it is bound to INADDR_ANY
问题
当我们将一个UDP服务器套接字(IP/端口)绑定到特殊的IP地址INADDR_ANY时,系统中所有可用的接口将用于端口PORT。
现在实际上我需要在客户端连接时找到接口的MTU - 因此我需要找到客户端连接到的接口的详细信息。
我尝试使用getsockname
API,但它返回了"0.0.0.0"。我如何获取客户端连接到的接口的实际IP地址?
英文:
When we bind a UDP server socket (Ip / port) to a special IP address INADDR_ANY - all interfaces avaliable in the system will be used for port PORT.
Now actually I am in need to find the MTU of the interface when a client gets connected - so I need to find the interface details to which a client has connected to it.
I tried to make use of getsockname
API but it returned "0.0.0.0". How can I get the actual IP of the interface to which a client has gotten connected?
答案1
得分: 4
UDP没有连接,这就是为什么你无法按你想要的方式使用 getsockname()
。
如果你想要知道当绑定到 INADDR_ANY
时,每个数据报是由哪个接口接收的,你可以在套接字上启用 IP_PKTINFO
选项,然后使用 recvmsg()
而不是 recvfrom()
来读取数据报。recvmsg()
输出时填充的 msghdr
结构可用于确定接收接口。更多详细信息,请参阅 cmsg
宏。
参见 https://stackoverflow.com/questions/5281409/
英文:
There is no connection in UDP, that is why you can't use getsockname()
the way you want.
If you want to know which interface receives each datagram when bound to INADDR_ANY
, you can enable the IP_PKTINFO
option on the socket and then use recvmsg()
rather than recvfrom()
to read the datagrams. The msghdr
struct that recvmsg()
populates on output can be used to determine the receiving interface. See the cmsg
macros for more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论