74 lines
1.6 KiB
C
74 lines
1.6 KiB
C
#include "http/http_request.h"
|
|
#include "http/http_response.h"
|
|
#include <netinet/in.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <unistd.h>
|
|
|
|
#define DEFAULT_HTML "index.html"
|
|
|
|
int main() {
|
|
|
|
const int PORT = 8080;
|
|
|
|
int serverfd, clientfd;
|
|
ssize_t valread;
|
|
|
|
struct sockaddr_in address;
|
|
int opt = 1;
|
|
socklen_t addrlen = sizeof(address);
|
|
char request[BUFSIZ] = {0};
|
|
|
|
if ((serverfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
|
|
perror("socket failed");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
// Forcefully attaching socket to the port 8080
|
|
if (setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
|
|
perror("setsockopt");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
address.sin_family = AF_INET;
|
|
address.sin_addr.s_addr = INADDR_ANY;
|
|
address.sin_port = htons(PORT);
|
|
|
|
if (bind(serverfd, (struct sockaddr *)&address, sizeof(address)) < 0) {
|
|
perror("bind failed");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
if (listen(serverfd, 3) < 0) {
|
|
perror("listen");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
if ((clientfd = accept(serverfd, (struct sockaddr *)&address, &addrlen)) <
|
|
0) {
|
|
perror("accept");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
valread = read(clientfd, request,
|
|
1024 - 1); // subtract 1 for the null
|
|
// terminator at the end
|
|
HttpRequest *req = handle_request(request);
|
|
HttpResponse *res;
|
|
if (!strcmp(req->path, "/")) {
|
|
res = from_file("./" DEFAULT_HTML);
|
|
} else {
|
|
char path[] = ".";
|
|
strcat(path, req->path);
|
|
res = from_file(path);
|
|
}
|
|
free(req);
|
|
http_respond(*res, clientfd);
|
|
free_response(res);
|
|
|
|
// closing the connected socket
|
|
close(clientfd);
|
|
// closing the listening socket
|
|
close(clientfd);
|
|
|
|
return 0;
|
|
}
|