#include #include #include #include #include #include #include #include #include #include int main(int argc, char * argv[]) { int s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror("socket"); exit(1); } printf("socket s is %d\n", s); struct sockaddr_in server_address; server_address.sin_len = sizeof(server_address); server_address.sin_family = AF_INET; server_address.sin_port = htons(atol(argv[1])); server_address.sin_addr.s_addr = htonl(INADDR_ANY); int r = bind(s, (struct sockaddr *) & server_address, sizeof(server_address)); if (r < 0) { perror("bind"); exit(1); } r = listen(s, 3); if (r < 0) { perror("listen"); exit(1); } while (1) { struct sockaddr_in client_address; socklen_t size = sizeof(client_address); int cs = accept(s, (struct sockaddr *) & client_address, & size); if (cs < 0) { printf("it happened\n"); sleep(1); continue; } printf("socket cs is %d\n", cs); int ipi = client_address.sin_addr.s_addr; unsigned char * ip = (unsigned char *) & ipi; printf("connection from %hhu.%hhu.%hhu.%hhu port %hu\n", ip[0], ip[1], ip[2], ip[3], ntohs(client_address.sin_port)); printf(" or %s port %d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); char received[1024]; while (1) { r = read(cs, received, sizeof(received)); printf("read returned %d\n", r); if (r <= 0) break; write(1, received, r); } const char * response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"; write(cs, response, strlen(response)); response = "hello\r\n"; write(cs, response, strlen(response)); close(cs); } close(s); }