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));
35 hints.ai_flags = AI_NUMERICHOST;
36 #ifndef WANT_IPV6 /* do not convert ipv6 addresses */
37 hints.ai_family = AF_INET;
40 /* some getaddrinfo implementations require that ai_socktype is set. */
41 hints.ai_socktype = SOCK_STREAM;
43 /* silly, but ngircd stores UINT16 in server config, not string */
44 snprintf(portstr, sizeof(portstr), "%u", (unsigned int) port);
46 ret = getaddrinfo(ip_str, portstr, &hints, &res0);
50 assert(sizeof(*addr) >= res0->ai_addrlen);
51 if (sizeof(*addr) >= res0->ai_addrlen)
52 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
57 #else /* HAVE_GETADDRINFO */
59 memset(addr, 0, sizeof *addr);
60 #ifdef HAVE_sockaddr_in_len
61 addr->sin4.sin_len = sizeof(addr->sin4);
63 addr->sin4.sin_family = AF_INET;
64 # ifdef HAVE_INET_ATON
65 if (inet_aton(ip_str, &addr->sin4.sin_addr) == 0)
68 addr->sin4.sin_addr.s_addr = inet_addr(ip_str);
69 if (addr->sin4.sin_addr.s_addr == (unsigned) -1)
72 ng_ipaddr_setport(addr, port);
74 #endif /* HAVE_GETADDRINFO */
79 ng_ipaddr_setport(ng_ipaddr_t *a, UINT16 port)
88 assert(af == AF_INET || af == AF_INET6);
92 a->sin4.sin_port = htons(port);
95 a->sin6.sin6_port = htons(port);
100 assert(a->sin4.sin_family == AF_INET);
101 a->sin4.sin_port = htons(port);
102 #endif /* WANT_IPV6 */
108 ng_ipaddr_ipequal(const ng_ipaddr_t *a, const ng_ipaddr_t *b)
113 if (a->sa.sa_family != b->sa.sa_family)
115 assert(ng_ipaddr_salen(a) == ng_ipaddr_salen(b));
116 switch (a->sa.sa_family) {
118 return IN6_ARE_ADDR_EQUAL(&a->sin6.sin6_addr, &b->sin6.sin6_addr);
120 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
124 assert(a->sin4.sin_family == AF_INET);
125 assert(b->sin4.sin_family == AF_INET);
126 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
133 ng_ipaddr_tostr(const ng_ipaddr_t *addr)
135 static char strbuf[NG_INET_ADDRSTRLEN];
139 ng_ipaddr_tostr_r(addr, strbuf);
144 /* str must be at least NG_INET_ADDRSTRLEN bytes long */
146 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *str)
148 #ifdef HAVE_GETNAMEINFO
149 const struct sockaddr *sa = (const struct sockaddr *) addr;
154 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
155 str, NG_INET_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
158 * causes mis-interpretation of client host in e.g. /WHOIS
161 char tmp[NG_INET_ADDRSTRLEN] = "0";
162 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
163 tmp + 1, (socklen_t)sizeof(tmp) - 1,
164 NULL, 0, NI_NUMERICHOST);
166 strlcpy(str, tmp, NG_INET_ADDRSTRLEN);
171 abort(); /* WANT_IPV6 depends on HAVE_GETNAMEINFO */
175 #endif /* WANT_IPV6 */