Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Tiny HTTP server to respond OK on port 9000 - handy for health checks on embedded boxes!
/**
* Based on http://tinyhack.com/2014/03/12/implementing-a-web-server-in-a-single-printf-call/
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<signal.h>
#include<fcntl.h>
int main(int argc, char *argv[])
{
int countforks = 0;
int waitint;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// If we don't do SO_REUSEADDR, the app fails to start sometime from connections
// of the last instance that are still around and not yet timed out.
int reuseaddr = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
struct sockaddr_in serv_addr;
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(9000);
bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
listen(sockfd, 5);
while (1) {
int cfd = accept(sockfd, 0, 0);
char *s = "HTTP/1.0 200\r\nContent-type:text/plain\r\n\r\nHello world!\r\n";
countforks++;
if (fork()==0) {
write(cfd, s, strlen(s));
shutdown(cfd, SHUT_RDWR);
close(cfd);
exit(0);
} else {
// because we listen in the main process the socket ends up open in both the child
// and the parent. We need to close it in the parent to prevent socket leakage.
close(cfd);
// We need to waitpid for all child processes to stop us having zombies piling up
int i; for (i=0; i<=countforks; i++) {
if (waitpid(-1, &waitint, WNOHANG)) {
countforks--;
}
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment