Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getaddrinfo with localhost: different behaviour when statically linked or not on same system

Tags:

c

getaddrinfo

I have a small c program which basically calls getaddrinfo. According to /etc/hosts localhost can be resolved to "127.0.0.1" and "::1".

Now when running the program the output depends on whether I compiled and linked using:

gcc -static test.c
$ a.out
127.0.0.1 2

gcc test.c
$ a.out
::1 10
127.0.0.1 2

I was checking which system calls have been done, and it seems that among other things the config file /etc/gai.conf was not used in the first case. However I wouldnt expect that gai.conf matters, because it is almost empty (except of a lot of comments.) And indeed if I remove the file, I am still able to correctly resolve (according to /etc/hosts) both ips with the dynmically linked program.

On the other hand does statically linking means in this case that even config files are evaluated at linking time ??

Question: Why the output of both program is different ?

test.c :

#include <netdb.h>
#include <stdio.h>

int main(int argc, char *argv[]) {

    struct addrinfo *result, *rp;
    int s = getaddrinfo("localhost", "", NULL, &result);
    char host[INET6_ADDRSTRLEN];
    for (rp = result; rp != NULL ; rp = rp->ai_next) {
        inet_ntop(rp->ai_family,
        (rp->ai_family == AF_INET ?
            &(((struct sockaddr_in*)rp->ai_addr)->sin_addr): 
                &(((struct sockaddr_in6*)rp->ai_addr)->sin6_addr)),
                host, sizeof host);
        printf("%s %d\n", host, rp->ai_family);
    }
}
like image 965
user1240076 Avatar asked Oct 20 '25 14:10

user1240076


1 Answers

under the glibc system, the implementation of RFC 3484 (address selection/ordering in IPv6) via getaddrinfo() is carried out through the gai.conf file if present which is the key element here as this is correct, and as it should be for the dynamically linked library call.

The fact that there is no system call being made to gai.conf in the statically linked library suggest strongly that there is a discrepancy between the two libraries regardless, and the fact that the sole address it returns is an IPv4 address is also concerning, as the implementation of RFC 3484 states that the default value returned is an IPv6 address, which we know exists from running the dynamically linked library call.

Without access to your system I would say there is a library file error here, rather than a coding error.