Skip to content

Instantly share code, notes, and snippets.

@alex14fr
Last active June 16, 2022 17:16
Show Gist options
  • Save alex14fr/e61b85e1380ee02e2d9d7dbcfa5e6d71 to your computer and use it in GitHub Desktop.
Save alex14fr/e61b85e1380ee02e2d9d7dbcfa5e6d71 to your computer and use it in GitHub Desktop.
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#define PORT 8000
#define OKMSG "HTTP/1.0 302 Found\r\nContent-length: 0\r\nLocation: https://avatar.spacefox.fr/Renard-%d.png\r\n\r\n"
#define MAXAVATARNR 21
#define MAXAVATARLEN 2
#define OUTLEN strlen(OKMSG)-2+MAXAVATARLEN
typedef struct {
int sock;
int rand;
} args_t;
void cleanup(void *a) {
close(((args_t*)a)->sock);
free(a);
}
void* handle_req(void *a) {
args_t *b=(args_t*)a;
pthread_cleanup_push(cleanup,b);
char out[OUTLEN];
int len=sprintf(out, OKMSG, b->rand);
write(b->sock, out, len);
pthread_cleanup_pop(1);
return(NULL);
}
args_t *a;
int main(int argc, char **argv) {
struct sockaddr_in addr;
int s=socket(AF_INET,SOCK_STREAM|SOCK_CLOEXEC,0);
int s2;
srand48(time(NULL));
if(s<0) { perror("socket"); exit(1); }
setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&(int){1},sizeof(int));
addr.sin_family=AF_INET;
addr.sin_port=htons(PORT);
addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
bind(s,(struct sockaddr*)&addr,sizeof(struct sockaddr_in));
if(listen(s,512)<0) { perror("listen"); exit(1); }
while((s2=accept(s,NULL,0))) {
a=malloc(sizeof(args_t));
a->sock=s2;
a->rand=1+drand48()*MAXAVATARNR;
pthread_t x;
pthread_create(&x,NULL,handle_req,a);
pthread_detach(x);
}
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment