2 * Functions for AF_ agnostic ipv4/ipv6 handling.
4 * (c) 2008 Florian Westphal <fw@strlen.de>, public domain.
11 #include <sys/socket.h>
12 #include <netinet/in.h>
14 #ifdef HAVE_ARPA_INET_H
15 # include <arpa/inet.h>
17 # define PF_INET AF_INET
22 #define NG_INET_ADDRSTRLEN INET6_ADDRSTRLEN
24 #define NG_INET_ADDRSTRLEN 16
31 struct sockaddr_in sin4;
32 struct sockaddr_in6 sin6;
35 /* assume compiler can't deal with typedef struct {... */
36 struct NG_IP_ADDR_DONTUSE {
37 struct sockaddr_in sin4;
39 typedef struct NG_IP_ADDR_DONTUSE ng_ipaddr_t;
44 ng_ipaddr_af(const ng_ipaddr_t *a)
47 return a->sa.sa_family;
49 assert(a->sin4.sin_family == 0 || a->sin4.sin_family == AF_INET);
50 return a->sin4.sin_family;
55 static inline socklen_t
56 ng_ipaddr_salen(const ng_ipaddr_t *a)
59 assert(a->sa.sa_family == AF_INET || a->sa.sa_family == AF_INET6);
60 if (a->sa.sa_family == AF_INET6)
61 return sizeof(a->sin6);
63 assert(a->sin4.sin_family == AF_INET);
64 return sizeof(a->sin4);
69 ng_ipaddr_getport(const ng_ipaddr_t *a)
72 int af = a->sa.sa_family;
74 assert(af == AF_INET || af == AF_INET6);
77 return ntohs(a->sin6.sin6_port);
78 #endif /* WANT_IPV6 */
79 assert(a->sin4.sin_family == AF_INET);
80 return ntohs(a->sin4.sin_port);
84 * init a ng_ipaddr_t object.
85 * @param addr: pointer to ng_ipaddr_t to initialize.
86 * @param ip_str: ip address in dotted-decimal (ipv4) or hexadecimal (ipv6) notation
87 * @param port: transport layer port number to use.
89 GLOBAL bool ng_ipaddr_init PARAMS((ng_ipaddr_t *addr, const char *ip_str, UINT16 port));
91 /* set sin4/sin6_port, depending on a->sa_family */
92 GLOBAL void ng_ipaddr_setport PARAMS((ng_ipaddr_t *a, UINT16 port));
94 /* return true if a and b have the same IP address. If a and b have different AF, return false. */
95 GLOBAL bool ng_ipaddr_ipequal PARAMS((const ng_ipaddr_t *a, const ng_ipaddr_t *b));
99 /* convert struct sockaddr to string, returns pointer to static buffer */
100 GLOBAL const char *ng_ipaddr_tostr PARAMS((const ng_ipaddr_t *addr));
102 /* convert struct sockaddr to string. dest must be NG_INET_ADDRSTRLEN bytes long */
103 GLOBAL bool ng_ipaddr_tostr_r PARAMS((const ng_ipaddr_t *addr, char *dest));
105 static inline const char *
106 ng_ipaddr_tostr(const ng_ipaddr_t *addr) { return inet_ntoa(addr->sin4.sin_addr); }
109 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *d)
111 strlcpy(d, inet_ntoa(addr->sin4.sin_addr), NG_INET_ADDRSTRLEN);