title: Why are there multiple results from getaddrinfo?
body: <p>I am trying to create a simple program that gets the IP address given a certain hostname:</p>
  <p>My code snipped is attached below:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char *argv[]) {
      if(argc &lt; 2){
          printf(&quot;Please provide a hostname.\n&quot;);
          exit(1);
      }
  
      char *hostname = argv[1];
      char ip[100];
      get_ip(hostname, ip);
      printf(&quot;%s resolved to %s\n&quot;, hostname,ip);
  }
  
  int get_ip(char *hostname, char *ip){
      struct sockaddr_in *h;
      int sockfd;
      struct addrinfo hints, *servinfo,*res;
      struct addrinfo *iter;
      int rv;
  
      memset(&amp;hints, 0, sizeof hints);
      hints.ai_family = AF_UNSPEC;
      hints.ai_socktype = SOCK_STREAM;
      if((rv = getaddrinfo(hostname, &quot;HTTP&quot;, &amp;hints, &amp;res)) != 0) {
          fprintf(stderr, &quot;getaddrinfo %s\n&quot;, gai_strerror(rv));
          return 1;
      }
      for(iter=res; iter != NULL; iter=iter-&gt;ai_next){
        printf(&quot;%p\n&quot;, iter-&gt;ai_next);
  
         h=(struct sockaddr_in *)iter-&gt;ai_addr;
         strcpy(IP, inet_ntoa(h-&gt;sin_addr));
         printf(&quot;%s\n&quot;,ip);
      }
      freeaddrinfo(res);
      return 0;
  }
  </code></pre>
  <p>I enter in the following arguments:</p>
  <pre><code>gcc get_ip_addr.c -o get_ip_addr;
  ./get_ip_addr google-public-dns-b.google.com
  </code></pre>
  <p>This results in:</p>
  <pre><code>0x2475330
  8.8.4.4
  (nil)
  0.0.0.0
  </code></pre>
  <p>When I remove the <code>&quot;http&quot;</code> and <code>&amp;hints</code> and set them to <code>NULL</code> I get the following results:</p>
  <pre><code>0x1b63310
  8.8.4.4
  0x1b63360
  8.8.4.4
  0x1b633b0
  8.8.4.4
  0x1b63410
  0.0.0.0
  0x1b63470
  0.0.0.0
  (nil)
  0.0.0.0
  </code></pre>
  <p>So when I set the <code>service</code> and <code>hints</code> to <code>NULL</code> the <code>getaddrinfo()</code> returns multiple possible results I don't understand why I am getting multiple IP addresses instead of just getting one IP address?</p>