xref: /minix3/external/bsd/bind/dist/lib/samples/sample-gai.c (revision 00b67f09dd46474d133c95011a48590a8e8f94c7)
1 /*	$NetBSD: sample-gai.c,v 1.1.1.4 2014/12/10 03:34:46 christos Exp $	*/
2 
3 /*
4  * Copyright (C) 2009, 2012-2014  Internet Systems Consortium, Inc. ("ISC")
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
11  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
13  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
15  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16  * PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /* Id: sample-gai.c,v 1.4 2009/09/02 23:48:02 tbox Exp  */
20 
21 #include <config.h>
22 
23 #include <isc/net.h>
24 
25 #include <irs/netdb.h>
26 
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdio.h>
30 
31 static void
do_gai(int family,char * hostname)32 do_gai(int family, char *hostname) {
33 	struct addrinfo hints, *res, *res0;
34 	int error;
35 	char namebuf[1024], addrbuf[1024], servbuf[1024];
36 
37 	memset(&hints, 0, sizeof(hints));
38 	hints.ai_family = family;
39 	hints.ai_socktype = SOCK_STREAM;
40 	hints.ai_flags = AI_CANONNAME;
41 	error = getaddrinfo(hostname, "http", &hints, &res0);
42 	if (error) {
43 		fprintf(stderr, "getaddrinfo failed for %s,family=%d: %s\n",
44 			hostname, family, gai_strerror(error));
45 		return;
46 	}
47 
48 	for (res = res0; res; res = res->ai_next) {
49 		error = getnameinfo(res->ai_addr,
50 				    (socklen_t)res->ai_addrlen,
51 				    addrbuf, sizeof(addrbuf),
52 				    NULL, 0, NI_NUMERICHOST);
53 		if (error == 0)
54 			error = getnameinfo(res->ai_addr,
55 					    (socklen_t)res->ai_addrlen,
56 					    namebuf, sizeof(namebuf),
57 					    servbuf, sizeof(servbuf), 0);
58 		if (error != 0) {
59 			fprintf(stderr, "getnameinfo failed: %s\n",
60 				gai_strerror(error));
61 		} else {
62 			printf("%s(%s/%s)=%s:%s\n", hostname,
63 			       res->ai_canonname, addrbuf, namebuf, servbuf);
64 		}
65 	}
66 
67 	freeaddrinfo(res0);
68 }
69 
70 int
main(int argc,char * argv[])71 main(int argc, char *argv[]) {
72 	if (argc < 2)
73 		exit(1);
74 
75 	do_gai(AF_INET, argv[1]);
76 	do_gai(AF_INET6, argv[1]);
77 	do_gai(AF_UNSPEC, argv[1]);
78 
79 	return (0);
80 }
81