Skip to content

Instantly share code, notes, and snippets.

@7etsuo
Created March 9, 2025 04:57
Show Gist options
  • Save 7etsuo/4160e75ffb5d4074887434af6ec45f08 to your computer and use it in GitHub Desktop.
Save 7etsuo/4160e75ffb5d4074887434af6ec45f08 to your computer and use it in GitHub Desktop.
fred.c
/** Uncle Fred
* Create an index.html and put in the same dir.
* Compile normally with cc -O2 -o http http.c, run sudo ./http 80, open your brosert and type: http://127.0.0.1/
*/
#include/* micro HTTP server */<stdio.h>
#include/* usage: ./http [port] */<stdlib.h>
#include/* */<string.h>
#include/* the default port is 8080, files are */<unistd.h>
#include/* read from the current directory */<netdb.h>
int main(int n,char**
V){int t=SOCK_STREAM,
N=SO_REUSEADDR,i=1,c=
htons(n
>1?atoi (V[1]): 101*80) ;struct sockaddr_in s
={(0)}; void*f= &s;char *m,b[1036];s.sin_port
=c;for( N=!((t= socket( s.sin_family=AF_INET,
#define http(c) setsock ##opt(\
t,SOL_S ##OCKET ,N,&i,c (i)),bi ##nd(t,f,c(s))<0)||
t,0))<0 ||(http (sizeof )listen (t,5))<<10;N&&(0)<=(c
=accept(t,0,0));close (c)){b[ n=recv( c,b,N,0),0>n?0:n]=0;n
=!memcmp(b,"GET /",5) <<6;for (i=4;n^ '?'&&n< 127&&n>
32;)n=b[++i];f=0;m=n? strcpy( b+i,b[i -1]-'/' ?"":"i"
"ndex." "html") ,printf ("%s\n" ,(5+b)) ,strstr
(b,"/." )||0==( f=fopen (&b[5], "rb"))?"404 Not Foun"
"d":"2" "00 OK" :"501 " "Not Implemented";for
((send) ((c),b, sprintf (b, "HTTP/1.1 %s\n"
"\r\n%" "s",m,f ?"":m), 0);f&&!
((send) (c,b+0, fread(b ,1,N,f)
,0)-N&&
fclose(
f)|404*
N););}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment