6 #include <event2/event.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
11 #include <sys/select.h>
15 static struct addrinfo *
16 _resolve (const char *str)
19 static struct addrinfo hints, *result = NULL;
20 struct addrinfo *rp = NULL;
26 memset (&hints, 0, sizeof (hints));
27 hints.ai_family = AF_INET; /* AF_UNSPEC */
28 hints.ai_socktype = SOCK_DGRAM;
29 r = getaddrinfo (NULL, str, &hints, &result);
31 fprintf (stderr, "getaddrinfo: %s\n", gai_strerror (r));
37 result = result->ai_next;
44 udp_free_polldata (struct polldata *data)
54 /* @return if select() returns error or timeout, return select()
55 else return value from invoked callback function */
57 udp_poll (struct polldata *data)
63 uint8_t buf[RS_MAX_PACKET_LEN];
66 FD_SET (data->s, &rfds);
68 timeout = data->timeout->tv_sec; /* Save from destruction (Linux). */
69 //fprintf (stderr, "calling select with timeout %ld\n", timeout);
70 r = select (data->s + 1, &rfds, NULL, NULL, data->timeout);
72 data->timeout->tv_sec = timeout; /* Restore. */
73 //fprintf (stderr, "select returning %d\n", r);
76 len = recv (data->s, buf, sizeof (buf), 0);
78 return data->cb (buf, len);
84 udp_server (const char *bindto, struct timeval *timeout, data_cb cb)
89 for (res = _resolve (bindto); res; res = _resolve (bindto))
91 s = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
94 if (bind (s, res->ai_addr, res->ai_addrlen) == 0)
106 struct polldata *data = malloc (sizeof (struct polldata));
108 memset (data, 0, sizeof (struct polldata));
113 data->timeout = malloc (sizeof (struct timeval));
114 assert (data->timeout);
115 memcpy (data->timeout, timeout, sizeof (struct timeval));
124 hd (const uint8_t *buf, ssize_t len)
128 printf ("# len: %ld\n", len);
129 for (i = 0; i < len; i++)
131 printf ("%02x%s", buf[i], (i+1) % 8 ? " " : " ");
132 if ((i + 1) % 16 == 0)