#include #include #include #include #include #include #include #include #include #include #include struct client_list_entry { int fd; struct in_addr ip; char ip_string[16]; }; struct client_list_entry client_list[10]; int client_count = 0; void *handle_all_clients(void* arg){ // One of potentially many client threads char new_message[1024]; ssize_t readlen; struct pollfd fds[10]; for(;;){ for(int i = 0; i < client_count; i++){ fds[i].fd = client_list[i].fd; fds[i].events = POLLIN; fds[i].revents = 0; } // We're ignoring a race condition int ready_count = poll(fds, client_count, 10); if(ready_count < 1) continue; for(int i = 0; i < client_count; i++){ if(fds[i].revents & POLLIN){ readlen = read(fds[i].fd, new_message, 1024); new_message[readlen] = 0; puts(new_message); } } } } int main(int argc, char ** argv){ struct sockaddr_in sad; sad.sin_port = htons(5143); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // Step 1 if(skt == -1){ perror("socket"); return 1; } if( bind(skt, (struct sockaddr*)(&sad), sizeof(struct sockaddr_in)) ){ // step 2 perror("bind"); return 1; } if( listen(skt, 5) ){ // step 3 perror("listen"); return 1; } pthread_t thread_reference; pthread_create(&thread_reference, 0, handle_all_clients, 0); while(1){ // Main thread int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); printf("Connection made from address %s\n", inet_ntoa(client_address.sin_addr)); client_list[client_count].fd = client_fd; client_list[client_count].ip = client_address.sin_addr; strcpy(client_list[client_count].ip_string, inet_ntoa(client_address.sin_addr)); client_count++; } return 0; }