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 poll (struct polldata *data)
53 FD_SET (data->s, &rfds);
55 timeout = data->timeout->tv_sec; /* Save from destruction (Linux). */
56 //fprintf (stderr, "calling select with timeout %ld\n", timeout);
57 r = select (data->s + 1, &rfds, NULL, NULL, data->timeout);
59 data->timeout->tv_sec = timeout; /* Restore. */
60 //fprintf (stderr, "select returning %d\n", r);
63 len = recv (data->s, buf, sizeof (buf), 0);
65 return data->cb (buf, len);
71 server (const char *bindto, struct timeval *timeout, data_cb cb)
76 for (res = _resolve (bindto); res; res = _resolve (bindto))
78 s = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
81 if (bind (s, res->ai_addr, res->ai_addrlen) == 0)
93 struct polldata *data = malloc (sizeof (struct polldata));
95 memset (data, 0, sizeof (struct polldata));
100 data->timeout = malloc (sizeof (struct timeval));
101 assert (data->timeout);
102 memcpy (data->timeout, timeout, sizeof (struct timeval));