/* Compile with gcc -oserver_seq server_seq.c */ #include #include #include #include #include #include #include #include int main() { const char* PORT = "7000"; struct addrinfo hint; hint.ai_flags = AI_PASSIVE; hint.ai_family = AF_UNSPEC; hint.ai_socktype = SOCK_STREAM; struct addrinfo* addrinfo_list; if (getaddrinfo(NULL, PORT, &hint, &addrinfo_list) != 0) { fprintf(stderr, "main():error with call to 'getaddrinfo()'\n"); exit(EXIT_FAILURE); } int server_fd; struct addrinfo* it; for (it = addrinfo_list; it != NULL; it = it->ai_next) { server_fd = socket(PF_INET, SOCK_STREAM, 0); if (server_fd == -1) { fprintf(stderr, "main(): cannot create socket"); continue; } if (bind(server_fd, it->ai_addr, it->ai_addrlen) == -1) { fprintf(stderr, "main(): cannot bind the address, exiting program\n"); continue; } int yes = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); break; } const unsigned int PENDING_SIZE = 5; if (listen(server_fd, PENDING_SIZE) == -1) { fprintf(stderr, "main(): cannot listen the address, exiting program\n"); exit(EXIT_FAILURE); } while (1) { struct sockaddr_in client_address; socklen_t client_address_len = sizeof(client_address); int client_fd = accept(server_fd, (struct sockaddr*)&client_address, &client_address_len); if (client_fd == -1) { printf("main(): cannot accept client, sleeping...\n"); sleep(5); } char addr_buf[INET_ADDRSTRLEN]; const char* client_address_s = inet_ntop(AF_INET, (const void*)&client_address, addr_buf, INET_ADDRSTRLEN); if (client_address_s == NULL) printf("main(): cannot read client address\n"); else printf("main(): client accepted from %s\n", client_address_s); sleep(10); const char* request = "Hello, World!"; if (send(client_fd, request, strlen(request), 0) == -1) { printf("main(): cannot send response\n"); close(client_fd); continue; } close(client_fd); } return EXIT_SUCCESS; }