9 #include <sys/socket.h>
16 struct utcp_connection *c;
22 ssize_t do_recv(struct utcp_connection *c, const void *data, size_t len) {
25 fprintf(stderr, "Error: %s\n", strerror(errno));
29 fprintf(stderr, "Connection closed by peer\n");
33 return write(1, data, len);
36 void do_accept(struct utcp_connection *nc, uint16_t port) {
37 utcp_accept(nc, do_recv, NULL);
41 ssize_t do_send(struct utcp *utcp, const void *data, size_t len) {
42 int s = *(int *)utcp->priv;
43 if(drand48() < dropout)
46 ssize_t result = send(s, data, len, MSG_DONTWAIT);
48 fprintf(stderr, "Error sending UDP packet: %s\n", strerror(errno));
52 int main(int argc, char *argv[]) {
56 if(argc < 2 || argc > 3)
59 bool server = argc == 2;
60 bool connected = false;
62 dropin = atof(getenv("DROPIN") ?: "0");
63 dropout = atof(getenv("DROPOUT") ?: "0");
66 struct addrinfo hint = {
67 .ai_flags = server ? AI_PASSIVE : 0,
68 .ai_socktype = SOCK_DGRAM,
71 getaddrinfo(server ? NULL : argv[1], server ? argv[1] : argv[2], &hint, &ai);
75 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
80 if(bind(s, ai->ai_addr, ai->ai_addrlen))
83 if(connect(s, ai->ai_addr, ai->ai_addrlen))
90 struct utcp *u = utcp_init(server ? do_accept : NULL, NULL, do_send, &s);
94 utcp_set_mtu(u, 1300);
95 utcp_set_user_timeout(u, 10);
98 c = utcp_connect(u, 1, do_recv, NULL);
100 struct pollfd fds[2] = {
101 {.fd = 0, .events = POLLIN | POLLERR | POLLHUP},
102 {.fd = s, .events = POLLIN | POLLERR | POLLHUP},
106 struct timeval timeout = utcp_timeout(u);
109 size_t max = c ? utcp_get_sndbuf_free(c) : 0;
114 poll(fds, 2, timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
116 poll(fds + 1, 1, timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
120 fprintf(stderr, "0");
121 ssize_t len = read(0, buf, max);
126 utcp_shutdown(c, SHUT_WR);
133 ssize_t sent = utcp_send(c, buf, len);
135 fprintf(stderr, "PANIEK: %zd != %zd\n", sent, len);
141 fprintf(stderr, "1");
142 struct sockaddr_storage ss;
143 socklen_t sl = sizeof ss;
144 int len = recvfrom(s, buf, sizeof buf, MSG_DONTWAIT, (struct sockaddr *)&ss, &sl);
146 fprintf(stderr, "Error receiving UDP packet: %s\n", strerror(errno));
150 if(!connect(s, (struct sockaddr *)&ss, sl))
152 if(drand48() >= dropin)
153 utcp_recv(u, buf, len);
156 timeout = utcp_timeout(u);