#include #include #include #include #include #include #include #include char buffer[1024]; struct client_info { int fd; struct sockaddr_in address; }; struct client_info *clients[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int client_count = 0; void* handle_client(void* param){ struct client_info *client = param; clients[client_count] = client; int our_client_number = client_count; client_count++; write(client->fd, "Good Morning", 13); printf("Connection made from address %s with fd %d\n", inet_ntoa(client->address.sin_addr), client->fd); size_t readlen; while(1){ readlen = read(client->fd, buffer, 1024); if(readlen < 1) break; for(int i = 0; i < client_count; i++){ if(clients[i]) write(clients[i]->fd, buffer, readlen); } } printf("Done with connection from address %s\n", inet_ntoa(client->address.sin_addr)); clients[our_client_number] = 0; close(client->fd); free(client); } int main(int argc, char ** argv){ struct sockaddr_in sad; sad.sin_port = htons(5141); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); bind(skt, (struct sockaddr *)(&sad), sizeof(struct sockaddr_in)); listen(skt, 5); socklen_t address_size = sizeof(struct sockaddr_in); for(;;){ struct client_info *new_client = malloc(sizeof(struct client_info)); new_client->fd = accept(skt, (struct sockaddr *)(&(new_client->address)), &address_size); // Start a new thread to deal with the new client pthread_t T; pthread_create(&T, 0, handle_client, new_client); } return 0; }