#include #include #include #include #include #include #include #define PORT 8080 void handle_client(int client) { ssize_t bytes_read; size_t bufsize = 1024; char buf[bufsize]; bytes_read = read(client, buf, bufsize - 1); if (bytes_read == -1) { fprintf(stderr, "Failed to read data. Error = %s\n", strerror(errno)); } printf("%s\n", buf); } int main() { int ret; int server = socket(AF_INET, SOCK_STREAM, 0); if (server == -1) { fprintf(stderr, "Couldn't create socket. Error = %s\n", strerror(errno)); return 1; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(PORT); ret = bind(server, (struct sockaddr*)&addr, sizeof(addr)); if (ret == -1) { fprintf(stderr, "Couldn't bind socket. Error = %s\n", strerror(errno)); return 1; } ret = listen(server, 3); if (ret == -1) { fprintf(stderr, "Cannot listen on socket. Error = %s", strerror(errno)); return 1; } int client; while(1) { client = accept(server, (struct sockaddr*)&addr, sizeof(addr)); if (client == -1) { fprintf(stderr, "Couldn't connect to client. Error = %s\n", strerror(errno)); } handle_client(client); close(client); } /* Unreacheable Code */ close(server); return 0; }