title: How to get site ip address using c
body: <p>I am trying to build a HTTP request using sockets in c.
  So, in order to navigate the socket to the correct site ip.
  I need to get the site ip.
  I have managed to get the host ip but that not always work.
  The following code gets the host ip:</p>
  
  <pre><code>host = gethostbyname(host_name);
  if (host != NULL) {
      memcpy(&amp;inp, host-&gt;h_addr_list[0], host-&gt;h_length);
      sprintf(ip, "%s", inet_ntoa(inp));
  }
  </code></pre>
  
  <p>But that not always work, for example if I want to send the socket to stackoverflow.com and get his HTML content.I used this code and the output was: "198.252.206.16".
  And if you enter that ip you can see that it is a wrong ip,so what can I do?
  Please help.</p>
  
  <p>P.S that this all my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;arpa/inet.h&gt; 
  #include &lt;errno.h&gt;
  #include &lt;assert.h&gt;
  
  int main(int argc, char **argv) {
  
      if (argc &lt; 2) {
          fprintf(stderr, "usage: %s domain_name\nE.g. %s www.yahoo.com/lalal.html\n", argv[0], argv[0]);
          return(0);
      }
  
  struct protoent *pr;
  struct in_addr inp;
  int x = 1;
  int ret;
  char buf[4192];
  char ip[16];
  struct hostent *host;
  int sock, bytes_recieved;
  struct sockaddr_in server_addr;
  
  char url[strlen(argv[1])];
  strcpy(url,argv[1]);
  char *index_page = strstr(argv[1], "/");
  char *host_name = strtok(url,"/");
  char message[4000];
  sprintf(message,"GET %s HTTP/1.1\r\nHost: %s\r\n\r\n",index_page,host_name);
  printf("%s",message);
  
  host = gethostbyname(host_name);
  if (host != NULL) {
      memcpy(&amp;inp, host-&gt;h_addr_list[0], host-&gt;h_length);
      sprintf(ip, "%s", inet_ntoa(inp));
  }
  else {
      printf("ERROR - Host ip was not found.\n\n");
      exit(1);
  }
  
  printf("%s\n",ip);
  
  pr = getprotobyname("tcp");
  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      perror("Socket");
      exit(1);
  }
  printf("%s\n",message);
  server_addr.sin_family = AF_INET;     
  server_addr.sin_port = htons(80);   
  server_addr.sin_addr = *((struct in_addr *)host-&gt;h_addr);
  bzero(&amp;(server_addr.sin_zero),8); 
  
  if (connect(sock, (struct sockaddr *)&amp;server_addr, sizeof(struct sockaddr)) == -1) {
      perror("Connect");
      exit(1);
  }
  
  write(sock, message, strlen(message));
  
  while ((ret = read(sock, buf, 4192)) != 0) {
      buf[ret]='\0';
      fwrite(buf, ret, sizeof(char), stdout);
      x++;
  }
  
  if (close(sock) == -1)
      printf("Close socket error\n");
  
  return 0;
  </code></pre>
  
  <p>}</p>