1 /* 2 * getaddrinfo(3) (name->address lookup) tester. 3 * 4 * Compile with: 5 * 6 * cc -o getaddrinfo getaddrinfo.c (BSD, Linux) 7 * 8 * cc -o getaddrinfo getaddrinfo.c -lsocket -lnsl (SunOS 5.x) 9 * 10 * Run as: getaddrinfo hostname 11 * 12 * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. 13 * 14 * Author: Wietse Venema, IBM T.J. Watson Research, USA. 15 */ 16#include <sys/types.h> 17#include <sys/socket.h> 18#include <netinet/in.h> 19#include <arpa/inet.h> 20#include <netdb.h> 21#include <stdio.h> 22#include <unistd.h> 23#include <string.h> 24#include <stdlib.h> 25 26int main(int argc, char **argv) 27{ 28 char hostbuf[NI_MAXHOST]; /* XXX */ 29 struct addrinfo hints; 30 struct addrinfo *res0; 31 struct addrinfo *res; 32 const char *addr; 33 int err; 34 35#define NO_SERVICE ((char *) 0) 36 37 if (argc != 2) { 38 fprintf(stderr, "usage: %s hostname\n", argv[0]); 39 exit(1); 40 } 41 memset((char *) &hints, 0, sizeof(hints)); 42 hints.ai_family = PF_UNSPEC; 43 hints.ai_flags = AI_CANONNAME; 44 hints.ai_socktype = SOCK_STREAM; 45 if ((err = getaddrinfo(argv[1], NO_SERVICE, &hints, &res0)) != 0) { 46 fprintf(stderr, "host %s not found: %s\n", argv[1], gai_strerror(err)); 47 exit(1); 48 } 49 printf("Hostname:\t%s\n", res0->ai_canonname); 50 printf("Addresses:\t"); 51 for (res = res0; res != 0; res = res->ai_next) { 52 addr = (res->ai_family == AF_INET ? 53 (char *) &((struct sockaddr_in *) res->ai_addr)->sin_addr : 54 (char *) &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr); 55 if (inet_ntop(res->ai_family, addr, hostbuf, sizeof(hostbuf)) == 0) { 56 perror("inet_ntop:"); 57 exit(1); 58 } 59 printf("%s ", hostbuf); 60 } 61 printf("\n"); 62 freeaddrinfo(res0); 63 exit(0); 64} 65