moving from gitlab
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define BUFFER_SIZE 1024
|
||||
#define PORT 9090
|
||||
|
||||
char *parseRoute(const char *route) {
|
||||
|
||||
if (strcmp(route, "home") == 0) {
|
||||
return "./static/index.html";
|
||||
} else if (strcmp(route, "about") == 0) {
|
||||
return "./static/about.html";
|
||||
} else if (strcmp(route, "favicon.ico") == 0) {
|
||||
return "./static/favicon.ico";
|
||||
} else {
|
||||
return "./static/notFound.html";
|
||||
}
|
||||
}
|
||||
|
||||
void sendHtml(int *sock, const char *route) {
|
||||
// open our html file
|
||||
FILE *html = fopen(route, "r");
|
||||
if (!html) {
|
||||
perror("Error opening html file");
|
||||
return;
|
||||
}
|
||||
|
||||
char buf[BUFFER_SIZE] = {0};
|
||||
size_t read = 0;
|
||||
|
||||
char *header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
|
||||
send(*sock, header, strlen(header), 0);
|
||||
|
||||
while ((read = fread(buf, sizeof(buf[0]), BUFFER_SIZE, html)) > 0) {
|
||||
send(*sock, buf, read, 0);
|
||||
}
|
||||
fclose(html);
|
||||
}
|
||||
|
||||
int main() {
|
||||
int serverSocket;
|
||||
|
||||
if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
|
||||
perror("socket failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
struct sockaddr_in serverAddr;
|
||||
serverAddr.sin_family = AF_INET;
|
||||
serverAddr.sin_addr.s_addr = INADDR_ANY;
|
||||
serverAddr.sin_port = htons(PORT);
|
||||
|
||||
if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof serverAddr) <
|
||||
0) {
|
||||
perror("bind failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (listen(serverSocket, 5) < 0) {
|
||||
perror("listen failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
printf("Server listening on port %d\n", PORT);
|
||||
|
||||
while (1) {
|
||||
|
||||
struct sockaddr_in clientAddr;
|
||||
socklen_t clientAddr_len = sizeof clientAddr;
|
||||
int *clientSocket = malloc(sizeof(int));
|
||||
|
||||
if ((*clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr,
|
||||
&clientAddr_len)) < 0) {
|
||||
perror("accept failed");
|
||||
continue;
|
||||
}
|
||||
|
||||
printf("Connected\n");
|
||||
|
||||
char recBuf[BUFFER_SIZE] = {0};
|
||||
recv(*clientSocket, recBuf, BUFFER_SIZE, 0);
|
||||
// printf("%s\n", recBuf);
|
||||
|
||||
char *token = recBuf + 5;
|
||||
char *route = strtok(token, " ");
|
||||
|
||||
const char *file = parseRoute(route);
|
||||
sendHtml(clientSocket, file);
|
||||
|
||||
close(*clientSocket);
|
||||
printf("disconnected client.\n\n");
|
||||
}
|
||||
|
||||
close(serverSocket);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user