requests
This commit is contained in:
64
main.c
64
main.c
@@ -1,19 +1,65 @@
|
||||
#include "http/http_request.h"
|
||||
#include "http/http_response.h"
|
||||
#include "http/http_status.h"
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main() {
|
||||
|
||||
char body[BUFSIZ] = "<html><h1>Bonsoir</h1></html>";
|
||||
HttpResponse response = {.status_code = HTTP_OK,
|
||||
.content_type = HTTP_CT_HTML,
|
||||
.content_length = strlen(body),
|
||||
.body = body};
|
||||
const int PORT = 8080;
|
||||
|
||||
char out[BUFSIZ];
|
||||
construct_response(response, out);
|
||||
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);
|
||||
|
||||
printf("%s", out);
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user