2 * (c) 2008 Florian Westphal <fw@strlen.de>, public domain.
12 * Functions for AF_ agnostic ipv4/ipv6 handling (header).
17 #include <sys/socket.h>
18 #include <netinet/in.h>
20 #ifdef HAVE_ARPA_INET_H
21 # include <arpa/inet.h>
23 # define PF_INET AF_INET
28 #define NG_INET_ADDRSTRLEN INET6_ADDRSTRLEN
30 #define NG_INET_ADDRSTRLEN 16
37 struct sockaddr_in sin4;
38 struct sockaddr_in6 sin6;
41 /* assume compiler can't deal with typedef struct {... */
42 struct NG_IP_ADDR_DONTUSE {
43 struct sockaddr_in sin4;
45 typedef struct NG_IP_ADDR_DONTUSE ng_ipaddr_t;
50 ng_ipaddr_af(const ng_ipaddr_t *a)
54 return a->sa.sa_family;
56 assert(a->sin4.sin_family == 0 || a->sin4.sin_family == AF_INET);
57 return a->sin4.sin_family;
62 static inline socklen_t
63 ng_ipaddr_salen(const ng_ipaddr_t *a)
67 assert(a->sa.sa_family == AF_INET || a->sa.sa_family == AF_INET6);
68 if (a->sa.sa_family == AF_INET6)
69 return (socklen_t)sizeof(a->sin6);
71 assert(a->sin4.sin_family == AF_INET);
72 return (socklen_t)sizeof(a->sin4);
77 ng_ipaddr_getport(const ng_ipaddr_t *a)
80 int af = a->sa.sa_family;
83 assert(af == AF_INET || af == AF_INET6);
86 return ntohs(a->sin6.sin6_port);
87 #endif /* WANT_IPV6 */
90 assert(a->sin4.sin_family == AF_INET);
91 return ntohs(a->sin4.sin_port);
95 * init a ng_ipaddr_t object.
96 * @param addr: pointer to ng_ipaddr_t to initialize.
97 * @param ip_str: ip address in dotted-decimal (ipv4) or hexadecimal (ipv6) notation
98 * @param port: transport layer port number to use.
100 GLOBAL bool ng_ipaddr_init PARAMS((ng_ipaddr_t *addr, const char *ip_str, UINT16 port));
102 /* set sin4/sin6_port, depending on a->sa_family */
103 GLOBAL void ng_ipaddr_setport PARAMS((ng_ipaddr_t *a, UINT16 port));
105 /* return true if a and b have the same IP address. If a and b have different AF, return false. */
106 GLOBAL bool ng_ipaddr_ipequal PARAMS((const ng_ipaddr_t *a, const ng_ipaddr_t *b));
110 /* convert struct sockaddr to string, returns pointer to static buffer */
111 GLOBAL const char *ng_ipaddr_tostr PARAMS((const ng_ipaddr_t *addr));
113 /* convert struct sockaddr to string. dest must be NG_INET_ADDRSTRLEN bytes long */
114 GLOBAL bool ng_ipaddr_tostr_r PARAMS((const ng_ipaddr_t *addr, char *dest));
116 static inline const char*
117 ng_ipaddr_tostr(const ng_ipaddr_t *addr)
119 assert(addr != NULL);
120 return inet_ntoa(addr->sin4.sin_addr);
124 ng_ipaddr_tostr_r(const ng_ipaddr_t *addr, char *d)
126 assert(addr != NULL);
128 strlcpy(d, inet_ntoa(addr->sin4.sin_addr), NG_INET_ADDRSTRLEN);