I'm using getaddrinfo to start a local server accepting connections only on the localhost:
struct addrinfo *res;
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo(NULL, portbuf, &hints, &res);
This seems to work fine, giving me the IPv6 address ::1 when IPv6 is present and IPv4 address when it is not.
Except sometimes on Windows 2008 R2 (at least that's the only system where I've seen it,开发者_JAVA百科 but I saw it twice, both times on a customer system) it gets bound to 127.0.0.1 instead of IPv6! This then messes me up because if you bind ::1 it will accept both connections to 127.1 and to ::1, but if you bind 127.1, then IPv6 connections are not accepted.getaddrinfo()
returns you a list of matching addresses, in an unspecified order. You should traverse the list (following the ai_next
pointer), and create a listening socket bound to each address returned.
精彩评论