Skip to content

Instantly share code, notes, and snippets.

@hetelek
Created June 26, 2022 20:04
Show Gist options
  • Save hetelek/f663640211c3e0c96893b2acbe964611 to your computer and use it in GitHub Desktop.
Save hetelek/f663640211c3e0c96893b2acbe964611 to your computer and use it in GitHub Desktop.
Simple HTTP server in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
struct conn
{
int fd;
} conn;
void *processConn(struct conn *c)
{
printf("processing connection\n");
char url[100] = {0};
char buf[100] = {0};
int read_s = 0;
char read_some = 0;
while ((read_s = read(c->fd, &buf, sizeof(buf))) > 0)
{
if (strncmp(buf, "GET ", 5))
{
char *start = buf + 5;
char *end = strchr(start, ' ') + 1;
strncpy(url, start, end - start);
printf("got get: %s\n", url);
break;
}
}
const char *payload_format = "HTTP/1.1 200 OK\n\
Date: Mon, 20 Jun 2022 12:22:35 GMT\n\
Server: Hetelek/1.0.1 (MS)\n\
Last-Modified: Mon, 20 Jun 2022 12:22:35 GMT\n\
Content-Length: %d\n\
Content-Type: text/html\n\n\
%s";
int payload_max_size = strlen(payload_format) + strlen(url) + 100;
char payload[payload_max_size];
memset(payload, 0, payload_max_size);
sprintf(payload, payload_format, strlen(url), url);
write(c->fd, payload, strlen(payload));
close(c->fd);
free(c);
return NULL;
}
int main()
{
struct sockaddr_in sock_addr;
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(8080);
inet_aton("127.0.0.1", &sock_addr.sin_addr.s_addr);
int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
if (tcp_socket == -1)
{
printf("socket error\n");
return 1;
}
setsockopt(tcp_socket, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int));
int bind_ret = bind(tcp_socket, (struct sockaddr *)&sock_addr, sizeof(sock_addr));
if (bind_ret != 0)
{
printf("bind error: %d %s\n", errno, strerror(errno));
return 1;
}
printf("listening for connections...\n");
while (1)
{
int listen_fd = listen(tcp_socket, 0);
if (listen_fd == -1)
{
printf("listen error\n");
return 1;
}
struct sockaddr incoming_addr;
socklen_t addr_len;
int accept_fd = accept(tcp_socket, &incoming_addr, &addr_len);
if (accept_fd == -1)
{
printf("accept error\n");
return 1;
}
pthread_t thread_id;
struct conn *z = malloc(sizeof(conn));
z->fd = accept_fd;
pthread_create(&thread_id, NULL, processConn, z);
}
close(tcp_socket);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment