9 #include <sys/socket.h>
16 struct utcp_connection *c;
20 int do_recv(struct utcp_connection *c, const void *data, size_t len) {
23 fprintf(stderr, "Error: %s\n", strerror(errno));
27 fprintf(stderr, "Connection closed by peer\n");
31 return write(1, data, len);
34 void do_accept(struct utcp_connection *nc, uint16_t port) {
35 utcp_accept(nc, do_recv, NULL);
39 int do_send(struct utcp *utcp, const void *data, size_t len) {
40 int s = *(int *)utcp->priv;
41 return send(s, data, len, MSG_DONTWAIT);
44 int main(int argc, char *argv[]) {
47 if(argc < 2 || argc > 3)
50 bool server = argc == 2;
51 bool connected = false;
54 struct addrinfo hint = {
55 .ai_flags = server ? AI_PASSIVE : 0,
56 .ai_socktype = SOCK_DGRAM,
59 getaddrinfo(server ? NULL : argv[1], server ? argv[1] : argv[2], &hint, &ai);
63 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
68 if(bind(s, ai->ai_addr, ai->ai_addrlen))
71 if(connect(s, ai->ai_addr, ai->ai_addrlen))
76 struct utcp *u = utcp_init(server ? do_accept : NULL, NULL, do_send, &s);
80 utcp_set_connection_timeout(u, 10);
83 c = utcp_connect(u, 1, do_recv, NULL);
85 struct pollfd fds[2] = {
86 {.fd = 0, .events = POLLIN | POLLERR | POLLHUP},
87 {.fd = s, .events = POLLIN | POLLERR | POLLHUP},
91 int timeout = utcp_timeout(u);
94 poll(fds, 2, timeout);
97 int len = read(0, buf, sizeof buf);
102 utcp_shutdown(c, SHUT_WR);
109 utcp_send(c, buf, len);
113 struct sockaddr_storage ss;
115 int len = recvfrom(s, buf, sizeof buf, MSG_DONTWAIT, (struct sockaddr *)&ss, &sl);
119 if(!connect(s, (struct sockaddr *)&ss, sl))
121 utcp_recv(u, buf, len);
124 timeout = utcp_timeout(u);