实现参考:
- 《UNIX环境高级编程》16.3.3 地址查询
- 《UNIX系统编程手册 下》59.10.1
- man getaddrinfo
addr
: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using namespace std;
string getnameinfo_str(const sockaddr *addr, socklen_t addrlen, int flags) {
char host[NI_MAXHOST];
char service[NI_MAXSERV];
int ret = getnameinfo(addr, addrlen, host, sizeof(host), service, sizeof(service), flags);
if (ret != 0) {
fprintf(stderr, "getnameinfo failed, ret: %d, str: %s\n", ret, gai_strerror(ret));
}
return host + string(":") + service;
}
void work(const string &host, const string &service, int hints_flags, int getaddrinfo_flags) {
printf("host: %s, service: %s, hints_flags: %d, getaddrinfo_flags: %d\n", host.c_str(), service.c_str(), hints_flags, getaddrinfo_flags);
addrinfo hints;
addrinfo *result;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
hints.ai_flags = hints_flags;
int ret = getaddrinfo(host == "-" ? NULL : host.c_str(), service == "-" ? NULL : service.c_str(), &hints, &result);
if (ret != 0) {
fprintf(stderr, "getaddrinfo, host: %s, service: %s, ret: %d, str: %s\n", host.c_str(), service.c_str(), ret, gai_strerror(ret));
return;
}
for (addrinfo *p = result; p != NULL; p = p->ai_next) {
printf("addr: %s, flags: %d, family: %d, socktype: %d, procotol: %d\n",
getnameinfo_str(p->ai_addr, p->ai_addrlen, getaddrinfo_flags).c_str(), p->ai_flags, p->ai_family, p->ai_socktype, p->ai_protocol);
if (p == result && (hints_flags & AI_CANONNAME)) {
printf("canonname: %s\n", p->ai_canonname);
}
}
freeaddrinfo(result);
puts("-----------");
}
int main(int argc, char **argv) {
string host, service;
int hints_flags, getaddrinfo_flags;
while (cin >> host >> service >> hints_flags >> getaddrinfo_flags) {
work(host, service, hints_flags, getaddrinfo_flags);
}
work("-", "https", AI_PASSIVE, 0);
work("-", "https", 0, 0);
work("-", "https", AI_PASSIVE | AI_CANONNAME, 0);
work("127.0.0.1", "https", AI_PASSIVE, 0);
work("127.0.0.1", "https", AI_PASSIVE | AI_CANONNAME, 0);
work("127.0.0.1", "https", AI_PASSIVE | AI_CANONNAME, NI_NUMERICHOST | NI_NUMERICSERV);
work("localhost", "http", AI_CANONNAME, 0);
work("localhost", "http", AI_CANONNAME, NI_NUMERICHOST | NI_NUMERICSERV);
work("baidu.com", "http", AI_CANONNAME, 0);
work("baidu.com", "http", AI_CANONNAME, NI_NUMERICHOST | NI_NUMERICSERV);
work("google.com", "http", AI_CANONNAME, 0);
work("google.com", "http", AI_CANONNAME, NI_NUMERICHOST | NI_NUMERICSERV);
return 0;
}
1 | $ ./addr |