读取UDP广播的源地址

Read source address for UDP broadcast

我的目标是在广播地址范围 ff05:e671:2015::1 上监听 udp 数据报。收到后,恢复具体服务器ip。

目前,我正在接收有效数据包。但是,当我检查源地址时,这里有几个输出:

fd01:e671:2015:5c01::
fd01:e671:2015:d101::

这是我的代码的相关部分:

std::array<char, 1024> _buff;
sockaddr a {};
socklen_t s = sizeof( a );
auto bytes = recvfrom( _fd, _buff.data(), _buff.size(), MSG_DONTWAIT | MSG_TRUNC, &a, &s );
...
// reuse the buffer
sockaddr_in6 *sin = reinterpret_cast<sockaddr_in6*>( &a );
inet_ntop( AF_INET6, &sin->sin6_addr, _buff.data(), INET6_ADDRSTRLEN );

最后,这里是 tcpdump | grep fd01:e671:2015:5c01 的一些输出:

10:07:31.452905 IP6 fd01:e671:2015:5c01:203:2dff:fe34:d598.20001 > ff05:e671:2015:5c01:203:2dff:fe34:d598.20001: UDP, length 120
10:07:31.453122 IP6 fd01:e671:2015:5c01:203:2dff:fe34:d598.20001 > ff05:e671:2015:5c01:203:2dff:fe34:d598.20001: UDP, length 161
10:07:31.453128 IP6 fd01:e671:2015:5c01:203:2dff:fe34:d598.20001 > ff05:e671:2015:5c01:203:2dff:fe34:d598.20001: UDP, length 202
10:07:31.453130 IP6 fd01:e671:2015:5c01:203:2dff:fe34:d598.20001 > ff05:e671:2015:5c01:203:2dff:fe34:d598.20001: UDP, length 80
10:07:31.453131 IP6 fd01:e671:2015:5c01:203:2dff:fe34:d598.20001 > ff05:e671:2015:5c01:203:2dff:fe34:d598.20001: UDP, length 121
10:07:31.453133 IP6 fd01:e671:2015:5c01:203:2dff:fe34:d598.20001 > ff05:e671:2015:5c01:203:2dff:fe34:d598.20001: UDP, length 162

如何获取完整具体的数据报源ip?

您的 sockaddr 太小,无法容纳 IPv6 地址。您应该分配您打算持有的类型,并在对 recvfrom 的调用中强制转换。你不能反过来做,因为你实际上没有那样的 sockaddr_in6