Advertisement
bazz

getaddrinfo iteration example Mac OSX maybe *nix

Aug 13th, 2014
1,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. /*
  2.  
  3. getaddrinfo example
  4.  
  5. Authored by:
  6.     bazz
  7.  
  8. Built for/on OSX, and may be portable to other *nix based systems.
  9. This example demonstrates how to iterate over the linked list
  10. provided by getaddrinfo, to test for successful connection.
  11. Because, without testing, you're never sure that you are passing a
  12. successful ip!!
  13.  
  14. usage:
  15.  g++ getaddrinfo.cpp -o getaddrinfo
  16.  ./getaddrinfo google.com 80
  17.  ./getaddrinfo google.com http
  18.  same thing
  19.  
  20.  You will find that most cases succeed on first try.
  21.  Also, it takes awhile for connect to timeout,
  22.  how to adjust this?!
  23.  
  24. */
  25.  
  26.  
  27.  
  28. #include <iostream>
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <netdb.h>
  32. #include <err.h>
  33. #include <unistd.h>
  34. #include <arpa/inet.h>
  35.  
  36. int main(int argc, char **argv)
  37. {
  38.   struct addrinfo hints, *res, *res0;
  39.   int error;
  40.   int s;
  41.   const char *cause = NULL;
  42.   int index=0;
  43.   char ip[100];
  44.   struct sockaddr_in *h;
  45.  
  46.  
  47.   memset(&hints, 0, sizeof(hints));
  48.   hints.ai_family = PF_UNSPEC;
  49.   hints.ai_socktype = SOCK_STREAM;
  50.   error = getaddrinfo(argv[1], argv[2], &hints, &res0);
  51.   if (error)
  52.   {
  53.     errx(1, "%s", gai_strerror(error));
  54.     /*NOTREACHED*/
  55.   }
  56.   s = -1;
  57.   for (res = res0; res; res = res->ai_next)
  58.   {
  59.     index++;
  60.     s = socket(res->ai_family, res->ai_socktype,
  61.        res->ai_protocol);
  62.     if (s < 0)
  63.     {
  64.       std::cerr << "socket creation failed" << std::endl;
  65.       cause = "socket";
  66.       continue;
  67.     }
  68.  
  69.     h = (struct sockaddr_in *) res->ai_addr;
  70.     strcpy(ip , inet_ntoa( h->sin_addr ) );
  71.     std::cerr << "Trying to connect to " << ip << ":" << argv[2] << "; ";
  72.  
  73.     if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
  74.            std::cerr << "FAILED" << std::endl;
  75.            cause = "connect";
  76.            close(s);
  77.            s = -1;
  78.            continue;
  79.     }
  80.     std::cerr << "SUCCESS" << std::endl;
  81.     break;  /* okay we got one */
  82.   }
  83.   if (s < 0)
  84.   {
  85.     err(1, "%s", cause);
  86.     /*NOTREACHED*/
  87.   }
  88.  
  89.  
  90.   freeaddrinfo(res0);
  91.  
  92.   std::cout << "Connected to " << argv[1] << " at " << ip << " on try#" << index << std::endl;
  93.  
  94.   return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement