#include #include #include #include #include #include #include #define BUF_SIZE 500 int main (int argc, char *argv[]) { struct addrinfo hints; struct addrinfo *result, *rp; int s, j; char buf[BUF_SIZE]; if (argc != 3) { fprintf (stderr, "Usage: %s host port\n", argv[0]); exit (EXIT_FAILURE); } /* Obtain address(es) matching host/port */ memset (&hints, 0, sizeof (struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM; /* Datagram socket */ hints.ai_flags = AI_ADDRCONFIG; s = getaddrinfo (argv[1], argv[2], &hints, &result); if (s != 0) { fprintf (stderr, "getaddrinfo: %s\n", gai_strerror (s)); exit (EXIT_FAILURE); } /* getaddrinfo() returns a list of address structures. Try each address until we successfully connect(2). If socket(2) (or connect(2)) fails, we (close the socket and) try the next address. */ for (rp = result, j = 0; rp != NULL; rp = rp->ai_next) { if (0 == getnameinfo(rp->ai_addr, rp->ai_addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST)) { printf("Address %d: %s\n", ++j, buf); } else { printf("getnameinfo failed, skipping this address\n"); } } exit(EXIT_SUCCESS); }