Search code examples
socketsipv6getaddrinfo

How to deal with getaddrinfo and thread-safety?


I am using getaddrinfo for an IPv6-related C-project. The "man getaddrinfo" on my computer (uname -a: 3.5.0-23) only indicates that it is "reentrant". So I guess it is not thread-safe.

In scenarios where thread-safety is required, how to handle it? I also checked UNP but seems no concrete answer provided. Thanks a lot.


Solution

  • getaddrinfo() is indeed thread-safe. This is required by RFC 3493 Section 6.1:

    Functions getaddrinfo() and freeaddrinfo() must be thread-safe.

    On some platforms, gethostbyname() is thread-safe, but on others it is not. What gethostbyname() is not on all platforms is re-entrant. If you call gethostbyname() and then call gethostbyname() again in the same thread, the data from the first call is overwritten with data from the second call. This is because gethostbyname() usually uses a static buffer internally, that is why you have to copy the data before calling gethostbyname() again. getaddrinfo() does not suffer from that problem, as it allocates a new addrinfo struct every time it is called.