Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define handle_error(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)
int main(int argc, char **argv) {
int server_fd, client_fd;
struct sockaddr_in server_addr = {0}, client_addr;
socklen_t client_addr_size;
int yes = 1;
char buffer[10240];
ssize_t bytes;
size_t i;
const char response[] = "HTTP/1.1 200 Ok\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"a\r\n"
"0123456789\r\n"
"0\r\n"
"\r\n";
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1)
handle_error("socket");
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8080);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) ==
-1)
handle_error("bind");
if (listen(server_fd, 10) == -1)
handle_error("listen");
again:
client_addr_size = sizeof(client_addr);
client_fd =
accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_size);
if (client_fd == -1)
handle_error("accept");
bytes = read(client_fd, buffer, sizeof(buffer));
if (bytes < 0)
handle_error("read");
if (bytes == 0) {
close(client_fd);
goto again;
}
if (write(client_fd, response, strlen(response)) < 0)
handle_error("write");
bytes = read(client_fd, buffer, sizeof(buffer));
if (bytes < 0)
handle_error("read");
close(client_fd);
goto again;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment