MK.
MK.

Reputation: 34517

getaddrinfo inconsistent behavior

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, 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.

Upvotes: 1

Views: 488

Answers (1)

caf
caf

Reputation: 239011

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.

Upvotes: 3

Related Questions