#include #include #include #include #include #include #include #include #include #include struct client_args { int fd; struct in_addr ip; char ip_string[16]; }; void *client_function(void* arg){ struct client_args *ca = arg; printf("Connection made from address %s\n", ca->ip_string); // One of potentially many client threads write(ca->fd, "Good Morning\n", 13); char client_message[101]; ssize_t readlen; while((readlen = read(ca->fd, client_message, 100)) > 0) { client_message[readlen] = 0; printf("Client on %s sent: %s\n", ca->ip_string, client_message); } close(ca->fd); free(ca); } 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; } 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); pthread_t thread_reference; struct client_args *ca = malloc(sizeof(struct client_args)); ca->fd = client_fd; ca->ip = client_address.sin_addr; strcpy(ca->ip_string, inet_ntoa(ca->ip)); pthread_create(&thread_reference, 0, client_function, ca); } return 0; }