从 sockaddr_storage 检索 ip 和端口
我有一个 sockaddr_storage
,其中包含远程主机的 ipv4 地址和端口。不过,我之前没有见过这些 struct ,而且我不确定如何将其转换为可以直接检索 IP 地址和端口号的 struct 。我尝试用谷歌搜索struct
,但没有找到任何东西。关于如何执行此操作有什么建议吗?
谢谢
I've got a sockaddr_storage
containing the ipv4 address and port of a remote host. I haven't seen these struct
s before though and I'm not sure how to cast it into a struct
where I can directly retrieve IP address and port number. I've tried googling the struct
but haven't found anything. Any suggestions on how to do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将指针强制转换为 struct sockaddr_in * 或 struct sockaddr_in6 * 并直接访问成员,但这会引发大量有关别名冲突和错误编译问题的蠕虫病毒。
更好的方法是将指针传递给带有
NI_NUMERICHOST
和NI_NUMERICSERV
标志的getnameinfo
,以获取地址和端口的字符串表示形式。这样做的优点是它无需额外代码即可支持 IPv4 和 IPv6,并且理论上也支持所有未来的地址类型。您可能必须将指针强制转换为void *
(或显式地struct sockaddr *
,如果您使用的是 C++),以将其传递给getnameinfo
,但这不会引起问题。You can cast the pointer to
struct sockaddr_in *
orstruct sockaddr_in6 *
and access the members directly, but that's going to open a can of worms about aliasing violations and miscompilation issues.A better approach would be to pass the pointer to
getnameinfo
with theNI_NUMERICHOST
andNI_NUMERICSERV
flags to get a string representation of the address and port. This has the advantage that it supports both IPv4 and IPv6 with no additional code, and in theory supports all future address types too. You might have to cast the pointer tovoid *
(orstruct sockaddr *
explicitly, if you're using C++) to pass it togetnameinfo
, but this should not cause problems.要扩展上面的答案并提供使用
getnameinfo
函数的代码,请检查以下代码段:结果是
hoststr
包含来自struct sockaddr_storage
的 IP 地址code> 和portstr
分别包含一个端口。To extend an answer above and provide a code that uses
getnameinfo
function, check this snippet:The result is that a
hoststr
contains an IP address fromstruct sockaddr_storage
and aportstr
contains a port respectively.