initial import
[ICEs.git] / 199025 / getaddrinfo.c
1 #define _GNU_SOURCE
2 #include <netdb.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <arpa/inet.h>
7 #include <netinet/in.h>
8 #include <sys/socket.h>
9 #include <sys/types.h>
10
11 void doit(const char *name, const char *family_name, int family)
12 {
13 printf("--- looking up '%s' for family %s (%i)\n", name, family_name, family);
14
15 struct addrinfo hints;
16 memset(&hints, 0, sizeof(hints));
17 hints.ai_socktype = SOCK_STREAM;
18 hints.ai_flags = AI_NUMERICHOST;
19 hints.ai_family = family;
20
21 struct addrinfo *hostaddr = 0;
22 int res = getaddrinfo(name, "telnet", &hints, &hostaddr);
23 if (res == EAI_NONAME) {
24 printf("getaddrinfo(...) = EAI_NONAME, trying again with AI_CANONNAME\n");
25 hints.ai_flags = AI_CANONNAME;
26 res = getaddrinfo(name, "telnet", &hints, &hostaddr);
27 }
28 if (res == EAI_NONAME) {
29 printf("getaddrinfo(...) = EAI_NONAME ... FAIL\n");
30 } else if (res) {
31 printf("getaddrinfo(...) = %i ... FAIL\n", res);
32 } else {
33 printf("getaddrinfo(...) = %i\n", res);
34
35 while (hostaddr) {
36 char name[1024], service[1024];
37 res = getnameinfo(hostaddr->ai_addr, hostaddr->ai_addrlen,
38 name, sizeof(name), service, sizeof(service),
39 NI_NUMERICHOST | NI_NUMERICSERV);
40 printf("getnameinfo(...) = %i\n", res);
41 printf("\tname = %s\n", name);
42 printf("\tservice = %s\n", service);
43 hostaddr = hostaddr->ai_next;
44 }
45 }
46
47 freeaddrinfo(hostaddr);
48 }
49
50 int main(int argc, char *argv[])
51 {
52 const char *name = (argc > 1 ? argv[1] : "localhost");
53
54 #define doit(name, family) doit(name, #family, family)
55 doit(name, 0);
56 doit(name, AF_INET);
57 doit(name, AF_INET6);
58
59 puts("");
60
61 return 0;
62 }