OSDN Git Service

fix for FreeBSD 11.1.
[hmh/hhml.git] / lib / util_inet.cc
1 #include "util_inet.h"
2 #include "util_string.h"
3 #include "ustring.h"
4 #include <vector>
5 #include <netinet/in.h>
6 #include <netdb.h>
7 #include <string.h>
8 #include <sys/socket.h>
9 #include <sys/types.h>
10 #include <arpa/inet.h>
11
12 ustring  getnameinfo (const ustring& ip) {
13     struct sockaddr_in  sa;
14     char  host[NI_MAXHOST + 4];
15     char*  p;
16     umatch  m;
17     static uregex  re ("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$");
18
19     if (regex_search (ip, m, re)) {
20         memset (&sa, 0, sizeof (sa));
21         sa.sin_family = AF_INET;
22         p = (char*)&sa.sin_addr;
23         p[0] = strtoul(ustring (m[1].first, m[1].second));
24         p[1] = strtoul(ustring (m[2].first, m[2].second));
25         p[2] = strtoul(ustring (m[3].first, m[3].second));
26         p[3] = strtoul(ustring (m[4].first, m[4].second));
27         if (getnameinfo ((struct sockaddr*)&sa, sizeof (sa), host, NI_MAXHOST, NULL, 0, 0) == 0) {
28             return ustring (host);
29         }
30     }
31     return ip;
32 }
33
34 void  getAddrInfo (const ustring& hostname, std::vector<ustring>& ans) {
35     struct addrinfo*  ai;
36     struct addrinfo*  p;
37     char  b[INET6_ADDRSTRLEN];
38     ustring  ip;
39
40     if (getaddrinfo (hostname.c_str (), NULL, NULL, &ai) == 0) {
41         for (p = ai; p; p = p->ai_next) {
42             if (p->ai_socktype == SOCK_STREAM) {
43                 switch (p->ai_family) {
44                 case PF_INET:
45                     {
46                         struct sockaddr_in*  sa = (struct sockaddr_in*)p->ai_addr;
47                         ip.assign (inet_ntop (p->ai_family, &sa->sin_addr, b, INET_ADDRSTRLEN));
48                         ans.push_back (ip);
49                     }
50                     break;
51                 case PF_INET6:
52                     {
53                         struct sockaddr_in6*  sa = (struct sockaddr_in6*)p->ai_addr;
54                         ip.assign (inet_ntop (p->ai_family, &sa->sin6_addr, b, INET6_ADDRSTRLEN));
55                         ans.push_back (ip);
56                     }
57                     break;
58                 default:;
59                 }
60             }
61         }
62     } else {
63     }
64 }