2 * copyright (c) 2011 Emil Mikulic.
4 * addr.c: compound IPv4/IPv6 address
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
13 #include <string.h> /* for memcmp */
14 #include <netdb.h> /* for getaddrinfo */
16 int addr_equal(const struct addr
* const a
, const struct addr
* const b
)
18 if (a
->family
!= b
->family
)
20 if (a
->family
== IPv4
)
21 return (a
->ip
.v4
== b
->ip
.v4
);
23 assert(a
->family
== IPv6
);
24 return (memcmp(&(a
->ip
.v6
), &(b
->ip
.v6
), sizeof(a
->ip
.v6
)) == 0);
28 static char _addrstrbuf
[INET6_ADDRSTRLEN
];
29 const char *addr_to_str(const struct addr
* const a
)
31 if (a
->family
== IPv4
) {
34 return (inet_ntoa(in
));
36 assert(a
->family
== IPv6
);
37 inet_ntop(AF_INET6
, &(a
->ip
.v6
), _addrstrbuf
, sizeof(_addrstrbuf
));
42 int str_to_addr(const char *s
, struct addr
*a
)
44 struct addrinfo hints
, *ai
;
47 memset(&hints
, 0, sizeof(hints
));
48 hints
.ai_family
= AF_UNSPEC
;
49 hints
.ai_flags
= AI_NUMERICHOST
;
51 if ((ret
= getaddrinfo(s
, NULL
, &hints
, &ai
)) != 0)
54 if (ai
->ai_family
== AF_INET
) {
56 a
->ip
.v4
= ((const struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
57 } else if (ai
->ai_family
== AF_INET6
) {
60 ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
.s6_addr
,
70 /* vim:set ts=3 sw=3 tw=78 et: */