2 * (c) 2008 Florian Westphal <fw@strlen.de>, public domain.
9 * Functions for AF_ agnostic ipv4/ipv6 handling.
16 #ifdef HAVE_GETADDRINFO
18 #include <sys/types.h>
21 #include "ng_ipaddr.h"
24 ng_ipaddr_init(ng_ipaddr_t *addr, const char *ip_str, UINT16 port)
26 #ifdef HAVE_GETADDRINFO
29 struct addrinfo *res0;
30 struct addrinfo hints;
34 memset(&hints, 0, sizeof(hints));
36 hints.ai_flags = AI_NUMERICHOST;
38 #ifndef WANT_IPV6 /* do not convert ipv6 addresses */
39 hints.ai_family = AF_INET;
42 /* some getaddrinfo implementations require that ai_socktype is set. */
43 hints.ai_socktype = SOCK_STREAM;
45 /* silly, but ngircd stores UINT16 in server config, not string */
46 snprintf(portstr, sizeof(portstr), "%u", (unsigned int) port);
48 ret = getaddrinfo(ip_str, portstr, &hints, &res0);
52 assert(sizeof(*addr) >= res0->ai_addrlen);
53 if (sizeof(*addr) >= res0->ai_addrlen)
54 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
59 #else /* HAVE_GETADDRINFO */
61 memset(addr, 0, sizeof *addr);
62 #ifdef HAVE_sockaddr_in_len
63 addr->sin4.sin_len = sizeof(addr->sin4);
65 addr->sin4.sin_family = AF_INET;
66 # ifdef HAVE_INET_ATON
67 if (inet_aton(ip_str, &addr->sin4.sin_addr) == 0)
70 addr->sin4.sin_addr.s_addr = inet_addr(ip_str);
71 if (addr->sin4.sin_addr.s_addr == (unsigned) -1)
74 ng_ipaddr_setport(addr, port);
76 #endif /* HAVE_GETADDRINFO */
81 ng_ipaddr_setport(ng_ipaddr_t *a, UINT16 port)
90 assert(af == AF_INET || af == AF_INET6);
94 a->sin4.sin_port = htons(port);
97 a->sin6.sin6_port = htons(port);
100 #else /* WANT_IPV6 */
102 assert(a->sin4.sin_family == AF_INET);
103 a->sin4.sin_port = htons(port);
104 #endif /* WANT_IPV6 */
110 ng_ipaddr_ipequal(const ng_ipaddr_t *a, const ng_ipaddr_t *b)
115 if (a->sa.sa_family != b->sa.sa_family)
117 assert(ng_ipaddr_salen(a) == ng_ipaddr_salen(b));
118 switch (a->sa.sa_family) {
120 return IN6_ARE_ADDR_EQUAL(&a->sin6.sin6_addr, &b->sin6.sin6_addr);
122 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
126 assert(a->sin4.sin_family == AF_INET);
127 assert(b->sin4.sin_family == AF_INET);
128 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
135 ng_ipaddr_tostr(const ng_ipaddr_t *addr)
137 static char strbuf[NG_INET_ADDRSTRLEN];
141 ng_ipaddr_tostr_r(addr, strbuf);
146 /* str must be at least NG_INET_ADDRSTRLEN bytes long */
148 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *str)
150 #ifdef HAVE_GETNAMEINFO
151 const struct sockaddr *sa = (const struct sockaddr *) addr;
156 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
157 str, NG_INET_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
160 * causes mis-interpretation of client host in e.g. /WHOIS
163 char tmp[NG_INET_ADDRSTRLEN] = "0";
164 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
165 tmp + 1, (socklen_t)sizeof(tmp) - 1,
166 NULL, 0, NI_NUMERICHOST);
168 strlcpy(str, tmp, NG_INET_ADDRSTRLEN);
173 abort(); /* WANT_IPV6 depends on HAVE_GETNAMEINFO */
177 #endif /* WANT_IPV6 */