#include #include #include #include #include #include int main() { struct sockaddr_in addr; addr.sin_family = AF_INET; /* IPv4 */ addr.sin_port = htons(8000); /* Port */ addr.sin_addr.s_addr = INADDR_ANY; /* equals to 0.0.0.0 */ int sfd = socket(AF_INET, SOCK_STREAM, 0); if (sfd == -1) { perror("could not open socket"); return 1; } int opt = 1; setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); int bind_addr = bind(sfd, (struct sockaddr *)&addr, sizeof(addr)); if (bind_addr == -1) { perror("could not bind socket"); return 1; } int listen_addr = listen(sfd, 100); if (listen_addr == -1) { perror("could not listen"); return 1; } struct pollfd fds[256]; fds[0].fd = sfd; /* socket file descriptor */ fds[0].events = POLLIN; /* data to read */ nfds_t nfds = 1; /* non file descriptor. something with timeout */ while (1) { /* we start the polling here */ int ready = poll(fds, nfds, -1); /* poll to accept many conn simultaneously */ if (ready == -1) { perror("could not run poll"); return 1; } if (fds[0].revents & POLLIN) { /* we accept the connections */ int conn = accept(sfd, NULL, NULL); if (conn == -1) { perror("could not accept connection"); continue; /* if one client is not able to connect the server shall not die */ } fds[nfds].fd = conn; /* read */ fds[nfds].events = POLLIN; /* check if telnet client has something to say */ nfds++; } for (nfds_t i = 1; i < nfds; i++) { /* if client has something to say */ if (fds[i].revents & POLLIN) { char buf[1024]; ssize_t n = read(fds[i].fd, buf, sizeof(buf)); /* read the n which the client sent */ if (n <= 0) { /* close the connection if client disappeared or disconnected */ close(fds[i].fd); } else { /* send every n bytes to the other clients */ for (nfds_t j = 1; j < nfds; j++) { if (j != i) { write(fds[j].fd, buf, n); } } } } } } return 0; }