Skip to content

Instantly share code, notes, and snippets.

@alex14fr
Created June 16, 2022 21:50
Show Gist options
  • Save alex14fr/48af0cb92e21e24a823bb0ec1c74e0a7 to your computer and use it in GitHub Desktop.
Save alex14fr/48af0cb92e21e24a823bb0ec1c74e0a7 to your computer and use it in GitHub Desktop.
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.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
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);
if(bind(s,(struct sockaddr*)&addr,sizeof(struct sockaddr_in))<0) { perror("bind"); exit(1); }
if(listen(s,512)<0) { perror("listen"); exit(1); }
while((s2=accept(s,NULL,0))) {
char out[OUTLEN];
int len=sprintf(out, OKMSG, 1+(int)(drand48()*MAXAVATARNR));
send(s2, out, len, MSG_DONTWAIT);
close(s2);
}
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment