2 * Functions for AF_ agnostic ipv4/ipv6 handling.
4 * (c) 2008 Florian Westphal <fw@strlen.de>, public domain.
13 #ifdef HAVE_GETADDRINFO
15 #include <sys/types.h>
18 #include "ng_ipaddr.h"
21 ng_ipaddr_init(ng_ipaddr_t *addr, const char *ip_str, UINT16 port)
23 #ifdef HAVE_GETADDRINFO
26 struct addrinfo *res0;
27 struct addrinfo hints;
31 memset(&hints, 0, sizeof(hints));
32 hints.ai_flags = AI_NUMERICHOST;
33 #ifndef WANT_IPV6 /* do not convert ipv6 addresses */
34 hints.ai_family = AF_INET;
37 /* some getaddrinfo implementations require that ai_socktype is set. */
38 hints.ai_socktype = SOCK_STREAM;
40 /* silly, but ngircd stores UINT16 in server config, not string */
41 snprintf(portstr, sizeof(portstr), "%u", (unsigned int) port);
43 ret = getaddrinfo(ip_str, portstr, &hints, &res0);
47 assert(sizeof(*addr) >= res0->ai_addrlen);
48 if (sizeof(*addr) >= res0->ai_addrlen)
49 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
54 #else /* HAVE_GETADDRINFO */
56 memset(addr, 0, sizeof *addr);
57 #ifdef HAVE_sockaddr_in_len
58 addr->sin4.sin_len = sizeof(addr->sin4);
60 addr->sin4.sin_family = AF_INET;
61 # ifdef HAVE_INET_ATON
62 if (inet_aton(ip_str, &addr->sin4.sin_addr) == 0)
65 addr->sin4.sin_addr.s_addr = inet_addr(ip_str);
66 if (addr->sin4.sin_addr.s_addr == (unsigned) -1)
69 ng_ipaddr_setport(addr, port);
71 #endif /* HAVE_GETADDRINFO */
76 ng_ipaddr_setport(ng_ipaddr_t *a, UINT16 port)
85 assert(af == AF_INET || af == AF_INET6);
89 a->sin4.sin_port = htons(port);
92 a->sin6.sin6_port = htons(port);
97 assert(a->sin4.sin_family == AF_INET);
98 a->sin4.sin_port = htons(port);
99 #endif /* WANT_IPV6 */
105 ng_ipaddr_ipequal(const ng_ipaddr_t *a, const ng_ipaddr_t *b)
110 if (a->sa.sa_family != b->sa.sa_family)
112 assert(ng_ipaddr_salen(a) == ng_ipaddr_salen(b));
113 switch (a->sa.sa_family) {
115 return IN6_ARE_ADDR_EQUAL(&a->sin6.sin6_addr, &b->sin6.sin6_addr);
117 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
121 assert(a->sin4.sin_family == AF_INET);
122 assert(b->sin4.sin_family == AF_INET);
123 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
130 ng_ipaddr_tostr(const ng_ipaddr_t *addr)
132 static char strbuf[NG_INET_ADDRSTRLEN];
136 ng_ipaddr_tostr_r(addr, strbuf);
141 /* str must be at least NG_INET_ADDRSTRLEN bytes long */
143 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *str)
145 #ifdef HAVE_GETNAMEINFO
146 const struct sockaddr *sa = (const struct sockaddr *) addr;
151 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
152 str, NG_INET_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
155 * causes mis-interpretation of client host in e.g. /WHOIS
158 char tmp[NG_INET_ADDRSTRLEN] = "0";
159 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
160 tmp + 1, (socklen_t)sizeof(tmp) - 1,
161 NULL, 0, NI_NUMERICHOST);
163 strlcpy(str, tmp, NG_INET_ADDRSTRLEN);
168 abort(); /* WANT_IPV6 depends on HAVE_GETNAMEINFO */
172 #endif /* WANT_IPV6 */