Skip to content

Instantly share code, notes, and snippets.

@jkramer
Last active August 29, 2015 14:23
Show Gist options
  • Save jkramer/cf49e7de52cf654d9815 to your computer and use it in GitHub Desktop.
Save jkramer/cf49e7de52cf654d9815 to your computer and use it in GitHub Desktop.
Minimal HTTP service optimized for size for testing deployment of services or something
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <assert.h>
#include <time.h>
int main(int argc, const char ** argv) {
int p, c, s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in host;
char h[128] = { 0, };
assert(argc == 2);
assert(s != -1);
p = strtol(argv[1], NULL, 10);
assert(p > 0);
host.sin_family = PF_INET;
host.sin_port = htons(p);
host.sin_addr.s_addr = 0; // 0.0.0.0
assert(bind(s, (struct sockaddr *) & host, sizeof(struct sockaddr_in)) == 0);
assert(listen(s, 1024) == 0);
gethostname(h, sizeof(h));
signal(SIGPIPE, SIG_IGN);
while(1) {
char b[2 * 1024 * 1024] = { 0, };
ssize_t l;
time_t ts;
struct tm * t;
const char * head =
"HTTP/1.1 200 OK\r\n"
"Server: immoschleuder 1.0\r\n"
"Cache-Control: no-cache, no-store, must-revalidate\r\n"
"Pragma: no-cache\r\n"
"Expires: 0\r\n"
;
if((c = accept(s, NULL, NULL)) == -1)
continue;
write(c, head, strlen(head));
ts = time(NULL);
t = localtime(& ts);
strftime(b, sizeof(b), "Date: %a, %d %b %Y %H:%M:%S %Z\r\n", t); // Date: Mon, 15 Jun 2015 13:19:13 GMT
write(c, b, strlen(b));
l = read(c, b, sizeof(b));
write(c, "\r\nREQUEST:\n", 11);
write(c, b, l - 2);
write(c, "\nHOSTNAME:\n", 11);
write(c, h, strlen(h));
shutdown(c, SHUT_RDWR);
close(c);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment