Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- getaddrinfo example
- Authored by:
- bazz
- Built for/on OSX, and may be portable to other *nix based systems.
- This example demonstrates how to iterate over the linked list
- provided by getaddrinfo, to test for successful connection.
- Because, without testing, you're never sure that you are passing a
- successful ip!!
- usage:
- g++ getaddrinfo.cpp -o getaddrinfo
- ./getaddrinfo google.com 80
- ./getaddrinfo google.com http
- same thing
- You will find that most cases succeed on first try.
- Also, it takes awhile for connect to timeout,
- how to adjust this?!
- */
- #include <iostream>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netdb.h>
- #include <err.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- int main(int argc, char **argv)
- {
- struct addrinfo hints, *res, *res0;
- int error;
- int s;
- const char *cause = NULL;
- int index=0;
- char ip[100];
- struct sockaddr_in *h;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- error = getaddrinfo(argv[1], argv[2], &hints, &res0);
- if (error)
- {
- errx(1, "%s", gai_strerror(error));
- /*NOTREACHED*/
- }
- s = -1;
- for (res = res0; res; res = res->ai_next)
- {
- index++;
- s = socket(res->ai_family, res->ai_socktype,
- res->ai_protocol);
- if (s < 0)
- {
- std::cerr << "socket creation failed" << std::endl;
- cause = "socket";
- continue;
- }
- h = (struct sockaddr_in *) res->ai_addr;
- strcpy(ip , inet_ntoa( h->sin_addr ) );
- std::cerr << "Trying to connect to " << ip << ":" << argv[2] << "; ";
- if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
- std::cerr << "FAILED" << std::endl;
- cause = "connect";
- close(s);
- s = -1;
- continue;
- }
- std::cerr << "SUCCESS" << std::endl;
- break; /* okay we got one */
- }
- if (s < 0)
- {
- err(1, "%s", cause);
- /*NOTREACHED*/
- }
- freeaddrinfo(res0);
- std::cout << "Connected to " << argv[1] << " at " << ip << " on try#" << index << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement