9 #include <sys/socket.h>
16 struct utcp_connection *c;
20 int do_recv(struct utcp_connection *c, void *data, size_t len) {
23 fprintf(stderr, "Error: %s\n", strerror(errno));
26 fprintf(stderr, "Connection closed by peer\n");
30 return write(0, data, len);
33 void do_accept(struct utcp_connection *nc, uint16_t port) {
34 utcp_accept(nc, do_recv, NULL);
38 int do_send(struct utcp *utcp, void *data, size_t len) {
39 int s = *(int *)utcp->priv;
40 return send(s, data, len, MSG_DONTWAIT);
43 int main(int argc, char *argv[]) {
46 if(argc < 2 || argc > 3)
49 bool server = argc == 2;
50 bool connected = false;
53 struct addrinfo hint = {
54 .ai_flags = server ? AI_PASSIVE : 0,
55 .ai_socktype = SOCK_DGRAM,
58 getaddrinfo(server ? NULL : argv[1], server ? argv[1] : argv[2], &hint, &ai);
62 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
67 if(bind(s, ai->ai_addr, ai->ai_addrlen))
70 if(connect(s, ai->ai_addr, ai->ai_addrlen))
75 struct utcp *u = utcp_init(server ? do_accept : NULL, NULL, do_send, &s);
80 c = utcp_connect(u, 1, do_recv, NULL);
82 struct pollfd fds[2] = {
83 {.fd = 0, .events = POLLIN | POLLERR | POLLHUP},
84 {.fd = s, .events = POLLIN | POLLERR | POLLHUP},
90 int r = poll(fds, 2, 1000);
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);