Freigeben über


Getaddrinfo() returning 127.0.0.1 for the local machine

Hello everyone,

Getaddrinfo()
is an API that returns IP addresses for a passed in hostname. If the host has
multiple entries the results are returned in a linked list of addresses. The
hostname can either be the local machine name or a remote machine name.

A customer noticed that on one particular machine, after
installing MS12-032,
requests to look up the local machine name would return the loopback address,
127.0.0.1, and not the public IP address.

The customer’s code looked something like this:

struct addrinfo
*addrInfo,*ai,hints;

       struct sockaddr_in *sockaddr_ipv4;

       char szIP4[30];

memset(&hints, 0, sizeof(hints));

hints.ai_socktype = SOCK_STREAM;

hints.ai_family = AF_INET;

       addrInfo = NULL;

 

getaddrinfo( "computername", "0", &hints, &addrInfo );

 

ai = addrInfo;

 

while(ai != NULL)

       {      
            

              sockaddr_ipv4 = (struct sockaddr_in *) ai->ai_addr;

              sprintf(szIP4, "%s",
inet_ntoa(sockaddr_ipv4->sin_addr) );

              ai = ai->ai_next;

}

      

       printf("Address:
%s\n", szIP4);

 

One thing this code does is that it ends up using the last
IP address returned. Getaddrinfo() can return multiple entries and there is no
guarantee what order they will be returned in. Normally, there is only one IPv4
(AF_INET) address and this will work as expected, and did before the security
patch.

Two things were happening on the machine that returned the
wrong address.

1)     
This function had always returned multiple
addresses, it just so happens that the last one returned had been the one that
we wanted.

2)     
One of the IP addresses returned was the loop
back adapter address of 127.0.0.1.

After the security update, we changed the order that the IP
addresses were returned from the hosts file. The system administrator had added
2 entries to the local hosts file, the static public IP, and the loop back
address.

                192.168.15.8
      computername

                127.0.0.1              computername

Normally there is no reason to add 127.0.0.1 to the hosts
file. “Loopback” is usually what you want to resolve to 127.0.0.1, not the
actual computername, and it does this without an explicit entry in the hosts
file. The easiest way to work around this problem is to remove the 127.0.0.1
entry from the hosts file.