- struct sockaddr_in addr = { .sin_family = AF_INET };
- socklen_t len;
- int sock;
- sock = socket(AF_INET, SOCK_STREAM, 0);
- if (sock < 0)
- err(1, "socket");
- if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
- err(1, "setsockopt");
- if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
- err(1, "bind");
- len = sizeof(addr);
- if (getsockname(sock, (struct sockaddr *)&addr, &len) < 0)
- err(1, "getsockname");
- int port = ntohs(addr.sin_port);
- if (listen(sock, 1) < 0)
- err(1, "listen");
- /* Signal to client that server is ready. */
- if (write(pipewr, &port, sizeof(port)) != sizeof(port))
- err(1, "write pipe");
- len = sizeof(addr);
- alarm(1);
- int client = accept(sock, (struct sockaddr *)&addr, &len);
- if (client < 0)
- err(1, "accept");
- alarm(0);