+static int start_input_reader(void) {
+ if(stdin_sock_fd != -1) {
+ fprintf(stderr, "stdin thread can only be started once.\n");
+ return -1;
+ }
+
+ stdin_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
+
+ if(stdin_sock_fd < 0) {
+ fprintf(stderr, "Could not create server socket: %s\n", strerror(errno));
+ return -1;
+ }
+
+ struct sockaddr_in serv_sa;
+
+ memset(&serv_sa, 0, sizeof(serv_sa));
+
+ serv_sa.sin_family = AF_INET;
+
+ serv_sa.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
+
+ int res = bind(stdin_sock_fd, (struct sockaddr *)&serv_sa, sizeof(serv_sa));
+
+ if(res < 0) {
+ fprintf(stderr, "Could not bind socket: %s\n", strerror(errno));
+ goto server_err;
+ }
+
+ if(listen(stdin_sock_fd, 1) < 0) {
+ fprintf(stderr, "Could not listen: %s\n", strerror(errno));
+ goto server_err;
+ }
+
+ struct sockaddr_in connect_sa;
+
+ socklen_t addr_len = sizeof(connect_sa);
+
+ if(getsockname(stdin_sock_fd, (struct sockaddr *)&connect_sa, &addr_len) < 0) {
+ fprintf(stderr, "Could not determine the address of the stdin thread socket\n");
+ goto server_err;
+ }
+
+ if(verbose) {
+ fprintf(stderr, "stdin thread is listening on :%d\n", ntohs(connect_sa.sin_port));
+ }
+
+ pthread_t th;
+ int err = pthread_create(&th, NULL, stdin_reader_thread, NULL);
+
+ if(err) {
+ fprintf(stderr, "Could not start reader thread: %s\n", strerror(err));
+ goto server_err;
+ }
+
+ int client_fd = socket(AF_INET, SOCK_STREAM, 0);
+
+ if(client_fd < 0) {
+ fprintf(stderr, "Could not create client socket: %s\n", strerror(errno));
+ return -1;
+ }
+
+ if(connect(client_fd, (struct sockaddr *)&connect_sa, sizeof(connect_sa)) < 0) {
+ fprintf(stderr, "Could not connect: %s\n", strerror(errno));
+ closesocket(client_fd);
+ return -1;
+ }
+
+ return client_fd;
+
+server_err:
+
+ if(stdin_sock_fd != -1) {
+ closesocket(stdin_sock_fd);
+ stdin_sock_fd = -1;
+ }
+
+ return -1;
+}
+
+#endif // HAVE_MINGW
+