Last active
July 14, 2021 15:57
-
-
Save corny/e663f96d78f26e934e488a7cafe864b4 to your computer and use it in GitHub Desktop.
Redirecting HTTP server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CC=gcc | |
CFLAGS=-I. -Wall -Wextra | |
OBJ = redirect.o | |
redirect: $(OBJ) | |
$(CC) -o $@ $^ $(CFLAGS) | |
clean: | |
rm -f redirect redirect.o |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#define on_error(...) { fprintf(stderr, __VA_ARGS__); fprintf(stderr, "%s\n", strerror(errno)); fflush(stderr); exit(1); } | |
int main (int argc, char *argv[]) { | |
if (argc != 3) { | |
fprintf(stderr, "Usage: %s [port] [url]\n", argv[0]); | |
exit(2); | |
} | |
int port = atoi(argv[1]); | |
char *url = argv[2]; | |
int server_fd, client_fd, err; | |
char response[128]; | |
int response_len = snprintf(response, sizeof(response), "HTTP/1.0 302 Found\r\nLocation: %s\r\n", url); | |
if (response_len == sizeof(response)) { | |
fprintf(stderr, "URL too long\n"); | |
exit(2); | |
} | |
server_fd = socket(AF_INET, SOCK_STREAM, 0); | |
if (server_fd < 0) on_error("Could not create socket\n"); | |
struct sockaddr_in server = { | |
.sin_family = AF_INET, | |
.sin_port = htons(port), | |
.sin_addr.s_addr = htonl(INADDR_ANY), | |
}; | |
int opt_val = 1; | |
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt_val, sizeof opt_val); | |
err = bind(server_fd, (struct sockaddr *) &server, sizeof(server)); | |
if (err < 0) on_error("Could not bind socket\n"); | |
err = listen(server_fd, 128); | |
if (err < 0) on_error("Could not listen on socket\n"); | |
printf("Server is listening on %d, redirecting to %s\n", port, url); | |
while (1) { | |
client_fd = accept(server_fd, NULL, NULL); | |
if (client_fd < 0) { | |
fprintf(stderr, "Client accept failed: %s\n", strerror(errno)); | |
continue; | |
} | |
err = send(client_fd, response, response_len, 0); | |
if (err < 0) { | |
fprintf(stderr, "Client write failed: %s\n", strerror(errno)); | |
} | |
close(client_fd); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment