从 sockaddr_storage 检索 IP 和端口 [英] retrieving ip and port from a sockaddr_storage

查看:47
本文介绍了从 sockaddr_storage 检索 IP 和端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 sockaddr_storage 包含远程主机的 ipv4 地址和端口.我之前没有见过这些 struct ,我不确定如何将它转换为 struct ,在那里我可以直接检索 IP 地址和端口号.我试过谷歌搜索 struct 但没有找到任何东西.有关如何执行此操作的任何建议?

I've got a sockaddr_storage containing the ipv4 address and port of a remote host. I haven't seen these structs 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?

谢谢

推荐答案

您可以将指针强制转换为 struct sockaddr_in *struct sockaddr_in6 * 并直接访问成员,但这会打开一堆关于别名违规和错误编译问题的蠕虫.

You can cast the pointer to struct sockaddr_in * or struct sockaddr_in6 * and access the members directly, but that's going to open a can of worms about aliasing violations and miscompilation issues.

更好的方法是将指针传递给带有 NI_NUMERICHOSTNI_NUMERICSERV 标志的 getnameinfo 以获得地址的字符串表示和港口.其优点是无需额外代码即可支持 IPv4 和 IPv6,理论上也支持所有未来的地址类型.您可能必须将指针强制转换为 void *(或 struct sockaddr *,如果您使用的是 C++)以将其传递给 getnameinfo,但这应该不会导致问题.

A better approach would be to pass the pointer to getnameinfo with the NI_NUMERICHOST and NI_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 to void * (or struct sockaddr * explicitly, if you're using C++) to pass it to getnameinfo, but this should not cause problems.

这篇关于从 sockaddr_storage 检索 IP 和端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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