- sock = accept(sock, NULL, NULL);
- if(sock < 0) {
- fprintf(stderr, "Could not accept connection: %s\n", strerror(errno));
- return 1;
+ if(!datagram) {
+ if(listen(sock, 1)) {
+ fprintf(stderr, "Could not listen on socket: %s\n", strerror(errno));
+ return 1;
+ }
+ fprintf(stderr, "Listening...\n");
+
+ sock = accept(sock, NULL, NULL);
+ if(sock < 0) {
+ fprintf(stderr, "Could not accept connection: %s\n", strerror(errno));
+ return 1;
+ }
+ } else {
+ fprintf(stderr, "Listening...\n");
+
+ char buf[65536];
+ struct sockaddr addr;
+ socklen_t addrlen = sizeof addr;
+
+ if(recvfrom(sock, buf, sizeof buf, MSG_PEEK, &addr, &addrlen) <= 0) {
+ fprintf(stderr, "Could not read from socket: %s\n", strerror(errno));
+ return 1;
+ }
+
+ if(connect(sock, &addr, addrlen)) {
+ fprintf(stderr, "Could not accept connection: %s\n", strerror(errno));
+ return 1;
+ }