开发者

Checking the address family in socket programming

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 ???


You can't—inet_pton gives you either a struct in_addr (for AF_INET) or a struct in6_addr (for AF_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 a char[16] as the value passed into inet_pton:

struct in_addr peer_ip;
inet_pton(AF_INET, "127.0.0.1", &peer_ip);


You have to go higher up and use getaddrinfo instead of inet_pton (which doesn't handle IPv6 scopes) and instead of opaque buffers use struct sockaddr_storage and struct sockaddr pointers then you can immediately determine the family with ss.ss_family or sa.sa_family as appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜