Skip to content

Instantly share code, notes, and snippets.

@paulbarbu
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulbarbu/2aff20065795ab2df7ef to your computer and use it in GitHub Desktop.
Save paulbarbu/2aff20065795ab2df7ef to your computer and use it in GitHub Desktop.
Very simple HTTP daemon for a talk I'll be giving
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define ERR(s, f) do { perror(s); if(f) exit(1); } while(0)
const char *resp200 = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n"
"<!DOCTYPE html><html><head><meta charset=\"utf8\">"
"<title>Mini Server</title></head><body><h1>"
"Hello mini-server world!</h1></body></html>";
const char *resp501 = "HTTP/1.1 501 Not Implemented\r\n\r\n"
"501 Not Implemented";
const char *req = "GET / HTTP/1.1\r\n"
"Host: localhost:4321";
int main() {
char buf[1024];
memset(buf, 1024, 0);
int server = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == server) ERR("socket", 1);
const int val = 1;
if(-1 == setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) ERR("setsockopt", 1);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(4321);
if(-1 == bind(server, (struct sockaddr *)&addr, sizeof(struct sockaddr_in))) ERR("bind", 1);
if(-1 == listen(server, 1)) ERR("listen", 1);
do {
int client = accept(server, 0, 0);
if(-1 == client) ERR("accept", 0);
if(-1 == read(client, buf, 1024)) ERR("read", 0);
const char *r;
int size = 0;
if(NULL != strstr(buf, req))
{
r = resp200;
size = strlen(resp200);
}
else
{
r = resp501;
size = strlen(resp501);
}
if(-1 == write(client, r, size)) ERR("write", 0);
if(-1 == close(client)) ERR("close", 0);
} while(1);
return shutdown(server, 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment