1 // scratch program to mess with getaddrinfo
9 #include <glog/logging.h>
11 using namespace google
;
14 int main(int argc
, char* argv
[])
16 InitGoogleLogging(argv
[0]);
17 InstallFailureSignalHandler();
24 hints
.ai_family
= AF_UNSPEC
;
25 hints
.ai_socktype
= SOCK_STREAM
;
26 hints
.ai_flags
= AI_CANONNAME
;
27 hints
.ai_protocol
= 0; // any protocol
30 int err
= getaddrinfo(argv
[1], nullptr, &hints
, &result
);
32 cerr
<< "getaddrinfo failure: " << gai_strerror(err
) << '\n';
37 cerr
<< "no results\n";
41 for (addrinfo
* rp
= result
; rp
; rp
= rp
->ai_next
) {
42 switch (rp
->ai_family
) {
50 cout
<< "unknown ai_family " << rp
->ai_family
<< '\n';
54 switch (rp
->ai_socktype
) {
56 cout
<< " SOCK_STREAM";
59 cout
<< " SOCK_DGRAM";
62 cout
<< "unknown ai_socktype " << rp
->ai_socktype
<< '\n';
66 switch (rp
->ai_protocol
) {
68 cout
<< " IPPROTO_TCP";
71 cout
<< " IPPROTO_UDP";
74 cout
<< "unknown ai_protocol " << rp
->ai_protocol
<< '\n';
81 cout
<< "canonname == " << rp
->ai_canonname
<< '\n';
83 char net_addr
[INET6_ADDRSTRLEN
];
85 switch (rp
->ai_addrlen
) {
86 case sizeof(sockaddr_in
): {
87 CHECK(rp
->ai_family
== AF_INET
);
88 sockaddr_in
* sa
= reinterpret_cast<struct sockaddr_in
*>(rp
->ai_addr
);
89 inet_ntop(AF_INET
, &(sa
->sin_addr
), net_addr
, sizeof net_addr
);
92 case sizeof(sockaddr_in6
): {
93 CHECK(rp
->ai_family
== AF_INET6
);
94 sockaddr_in6
* sa
= reinterpret_cast<struct sockaddr_in6
*>(rp
->ai_addr
);
95 inet_ntop(AF_INET6
, &(sa
->sin6_addr
), net_addr
, sizeof net_addr
);
99 cout
<< "unknown ai_addrlen" << rp
->ai_addrlen
<< '\n';
103 char host
[NI_MAXHOST
];
104 char serv
[NI_MAXSERV
];
106 cout
<< "addr == " << net_addr
<< '\n';
108 if (AF_INET
== rp
->ai_family
) {
110 adr
.sin_family
= AF_INET
;
111 PCHECK(inet_pton(AF_INET
, net_addr
, &adr
.sin_addr
) == 1);
112 err
= getnameinfo(reinterpret_cast<sockaddr
*>(&adr
), sizeof adr
, host
,
113 sizeof host
, serv
, sizeof serv
, 0);
115 cerr
<< "4 getnameinfo failure: " << gai_strerror(err
) << '\n';
120 if (AF_INET6
== rp
->ai_family
) {
122 adr
.sin6_family
= AF_INET6
;
123 PCHECK(inet_pton(AF_INET6
, net_addr
, &adr
.sin6_addr
) == 1);
124 err
= getnameinfo(reinterpret_cast<sockaddr
*>(&adr
), sizeof adr
, host
,
125 sizeof host
, serv
, sizeof serv
, 0);
127 cerr
<< "6 getnameinfo failure: " << gai_strerror(err
) << '\n';
132 cout
<< "reverse == " << host
<< '\n';
135 freeaddrinfo(result
);