#include #include #include #include #include #include #define ARRAY_LEN(x) (sizeof(x)/sizeof(x[0])) int main() { int port = 12345; int stdin_fd = 0; int server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd == -1) { fprintf(stderr, "Failed to open socket\n"); return -1; } int on = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); struct sockaddr_in addr = { AF_INET, htons(port), 0 }; if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { fprintf(stderr, "Failed to bind\n"); return -1; } listen(server_fd, 10); int client_fd = accept(server_fd, NULL, NULL); while (true) { struct pollfd fds[] = { { .fd = stdin_fd , POLLIN, 0 }, { .fd = client_fd, POLLIN, 0 } }; poll(fds, ARRAY_LEN(fds), -1); char buffer[256] = { 0 }; if (fds[0].revents & POLLIN) { int read_bytes = read(stdin_fd, buffer, sizeof(buffer) - 1); send(client_fd, buffer, read_bytes, 0); } else if (fds[1].revents & POLLIN) { if (recv(client_fd, buffer, sizeof(buffer) - 1, 0) == 0) { return 0; } printf("%s\n", buffer); } } return 0; }