2 * Functions for AF_ agnostic ipv4/ipv6 handling.
4 * (c) 2008 Florian Westphal <fw@strlen.de>, public domain.
11 #ifdef HAVE_ARPA_INET_H
12 # include <arpa/inet.h>
14 # define PF_INET AF_INET
19 #define NG_INET_ADDRSTRLEN INET6_ADDRSTRLEN
21 #define NG_INET_ADDRSTRLEN 16
28 struct sockaddr_in sin4;
29 struct sockaddr_in6 sin6;
32 /* assume compiler can't deal with typedef struct {... */
33 struct NG_IP_ADDR_DONTUSE {
34 struct sockaddr_in sin4;
36 typedef struct NG_IP_ADDR_DONTUSE ng_ipaddr_t;
41 ng_ipaddr_af(const ng_ipaddr_t *a)
44 return a->sa.sa_family;
46 assert(a->sin4.sin_family == 0 || a->sin4.sin_family == AF_INET);
47 return a->sin4.sin_family;
52 static inline socklen_t
53 ng_ipaddr_salen(const ng_ipaddr_t *a)
56 assert(a->sa.sa_family == AF_INET || a->sa.sa_family == AF_INET6);
57 if (a->sa.sa_family == AF_INET6)
58 return sizeof(a->sin6);
60 assert(a->sin4.sin_family == AF_INET);
61 return sizeof(a->sin4);
66 ng_ipaddr_getport(const ng_ipaddr_t *a)
69 int af = a->sa.sa_family;
71 assert(af == AF_INET || af == AF_INET6);
74 return ntohs(a->sin6.sin6_port);
75 #endif /* WANT_IPV6 */
76 assert(a->sin4.sin_family == AF_INET);
77 return ntohs(a->sin4.sin_port);
81 * init a ng_ipaddr_t object.
82 * @param addr: pointer to ng_ipaddr_t to initialize.
83 * @param ip_str: ip address in dotted-decimal (ipv4) or hexadecimal (ipv6) notation
84 * if ip_str is NULL it is treated as 0.0.0.0/[::]
85 * @param port: transport layer port number to use.
87 GLOBAL bool ng_ipaddr_init PARAMS((ng_ipaddr_t *addr, const char *ip_str, UINT16 port));
89 /* set sin4/sin6_port, depending on a->sa_family */
90 GLOBAL void ng_ipaddr_setport PARAMS((ng_ipaddr_t *a, UINT16 port));
92 /* return true if a and b have the same IP address. If a and b have different AF, return false. */
93 GLOBAL bool ng_ipaddr_ipequal PARAMS((const ng_ipaddr_t *a, const ng_ipaddr_t *b));
97 /* convert struct sockaddr to string, returns pointer to static buffer */
98 GLOBAL const char *ng_ipaddr_tostr PARAMS((const ng_ipaddr_t *addr));
100 /* convert struct sockaddr to string. dest must be NG_INET_ADDRSTRLEN bytes long */
101 GLOBAL bool ng_ipaddr_tostr_r PARAMS((const ng_ipaddr_t *addr, char *dest));
103 static inline const char *
104 ng_ipaddr_tostr(const ng_ipaddr_t *addr) { return inet_ntoa(addr->sin4.sin_addr); }
107 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *d)
109 strlcpy(d, inet_ntoa(addr->sin4.sin_addr), NG_INET_ADDRSTRLEN);