检查套接字编程中的地址族
以下代码的输出是什么:
char peer_ip[16];
inet_pton(AF_INET,"127.0.0.1",peer_ip);
现在我有网络形式的peer_ip。我怎样才能检查地址族是什么???我现在无法使用inet_ntop。有什么办法吗??在这种情况下 getaddrinfo 会起作用吗???
what will be the output of the following code :
char peer_ip[16];
inet_pton(AF_INET,"127.0.0.1",peer_ip);
now I have peer_ip in network form. How can I check what is the address family ??? I cannot use inet_ntop now. Is there any way ?? Will getaddrinfo work in this case ???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能 -
inet_pton
为你提供一个struct in_addr
(对于AF_INET
)或一个struct in6_addr
(对于AF_INET6
),具体取决于您传入的地址族。如果您将这些结构视为内存的二进制 blob,则无法从中恢复地址族,您只需跟踪你有什么类型的二进制 blob。您确实应该使用
struct in_addr
,而不是char[16]
作为传递到inet_pton
的值:You can't—
inet_pton
gives you either astruct in_addr
(forAF_INET
) or astruct in6_addr
(forAF_INET6
), depending on what address family you pass in. If you consider these structures to be binary blobs of memory, there's no way you can recover the address family from them, you just have to keep track of what type of binary blob you have.You should really be using a
struct in_addr
, not achar[16]
as the value passed intoinet_pton
:您必须走得更高,使用
getaddrinfo
而不是inet_pton
(它不处理 IPv6 范围),并且使用struct sockaddr_storage
而不是不透明缓冲区和 struct sockaddr 指针,那么您可以根据需要立即确定使用 ss.ss_family 或 sa.sa_family 的系列。You have to go higher up and use
getaddrinfo
instead ofinet_pton
(which doesn't handle IPv6 scopes) and instead of opaque buffers usestruct sockaddr_storage
andstruct sockaddr
pointers then you can immediately determine the family withss.ss_family
orsa.sa_family
as appropriate.