Files
cweb/main.c
2024-11-07 12:02:29 +01:00

66 lines
1.5 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>
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);
// print_request(req);
HttpResponse *res = from_file("./index.html");
http_respond(*res, clientfd);
free_response(res);
printf("Hello message sent\n");
// closing the connected socket
close(clientfd);
// closing the listening socket
close(clientfd);
return 0;
}