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;
34 /* some getaddrinfo implementations require that ai_socktype is set. */
35 hints.ai_socktype = SOCK_STREAM;
37 /* silly, but ngircd stores UINT16 in server config, not string */
38 snprintf(portstr, sizeof(portstr), "%u", (unsigned int) port);
40 ret = getaddrinfo(ip_str, portstr, &hints, &res0);
45 assert(sizeof(*addr) >= res0->ai_addrlen);
46 if (sizeof(*addr) >= res0->ai_addrlen)
47 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
52 #else /* HAVE_GETADDRINFO */
54 memset(addr, 0, sizeof *addr);
55 #ifdef HAVE_sockaddr_in_len
56 addr->sin4.sin_len = sizeof(addr->sin4);
58 addr->sin4.sin_family = AF_INET;
59 # ifdef HAVE_INET_ATON
60 if (inet_aton(ip_str, &addr->sin4.sin_addr) == 0)
63 addr->sin4.sin_addr.s_addr = inet_addr(ip_str);
64 if (addr->sin4.sin_addr.s_addr == (unsigned) -1)
67 ng_ipaddr_setport(addr, port);
69 #endif /* HAVE_GETADDRINFO */
74 ng_ipaddr_setport(ng_ipaddr_t *a, UINT16 port)
83 assert(af == AF_INET || af == AF_INET6);
87 a->sin4.sin_port = htons(port);
90 a->sin6.sin6_port = htons(port);
95 assert(a->sin4.sin_family == AF_INET);
96 a->sin4.sin_port = htons(port);
97 #endif /* WANT_IPV6 */
103 ng_ipaddr_ipequal(const ng_ipaddr_t *a, const ng_ipaddr_t *b)
108 if (a->sa.sa_family != b->sa.sa_family)
110 assert(ng_ipaddr_salen(a) == ng_ipaddr_salen(b));
111 switch (a->sa.sa_family) {
113 return IN6_ARE_ADDR_EQUAL(&a->sin6.sin6_addr, &b->sin6.sin6_addr);
115 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
119 assert(a->sin4.sin_family == AF_INET);
120 assert(b->sin4.sin_family == AF_INET);
121 return memcmp(&a->sin4.sin_addr, &b->sin4.sin_addr, sizeof(a->sin4.sin_addr)) == 0;
128 ng_ipaddr_tostr(const ng_ipaddr_t *addr)
130 static char strbuf[NG_INET_ADDRSTRLEN];
134 ng_ipaddr_tostr_r(addr, strbuf);
139 /* str must be at least NG_INET_ADDRSTRLEN bytes long */
141 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *str)
143 #ifdef HAVE_GETNAMEINFO
144 const struct sockaddr *sa = (const struct sockaddr *) addr;
149 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
150 str, NG_INET_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
153 * causes mis-interpretation of client host in e.g. /WHOIS
156 char tmp[NG_INET_ADDRSTRLEN] = "0";
157 ret = getnameinfo(sa, ng_ipaddr_salen(addr),
158 tmp + 1, (socklen_t)sizeof(tmp) - 1,
159 NULL, 0, NI_NUMERICHOST);
161 strlcpy(str, tmp, NG_INET_ADDRSTRLEN);
166 abort(); /* WANT_IPV6 depends on HAVE_GETNAMEINFO */
170 #endif /* WANT_IPV6 */