Fennet
Lightweight HTTP server library for C
Loading...
Searching...
No Matches
main.c File Reference

HelloServer example. More...

#include <fennet/lib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

Go to the source code of this file.

Macros

#define PORT   8080
 

Functions

int main (int argc, char **argv)
 Entry point of the HelloServer Example. More...
 

Detailed Description

HelloServer example.

HelloServer is a simple example of fennet's usage, it serves an HTTP server that always responds with the text "Hello!".

Definition in file main.c.

Macro Definition Documentation

◆ PORT

#define PORT   8080

Definition at line 21 of file main.c.

Function Documentation

◆ main()

int main ( int  argc,
char **  argv 
)

Entry point of the HelloServer Example.

 * 

Definition at line 27 of file main.c.

28{
29#ifndef _WIN32
30 // Socket interface initialisation
31 int main_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
32 if (main_socket == -1) {
33 printf("Couldn't initialise the main socket.\n");
34 }
35 printf("Initialised the main socket!\n");
36
37 // The address we want to be bound as
38 struct sockaddr_in address = {
39 AF_INET, htons(PORT), { htonl(INADDR_ANY) }, {}
40 };
41
42 // Bind to the address
43 if (bind(main_socket, (const struct sockaddr*)&address, sizeof(address))) {
44 printf("Socket couldn't be bound.\n");
45 return 1;
46 }
47 printf("Socket bound!\n");
48
49 // Listen for new connections on socket
50 if (listen(main_socket, 15)) {
51 printf("Socket couldn't be listened on.\n");
52 return 1;
53 }
54 printf("Listening on socket!\n");
55
56 // Determine whether
57 struct sockaddr_in client_address = {};
58 unsigned int client_address_size = sizeof(client_address);
59 int connection = accept(
60 main_socket, (struct sockaddr*)&client_address, &client_address_size);
61 if (connection < 0) {
62 printf("Accept failed.\n");
63 }
64 printf("Client accepted!\n");
65
66 // Receive HTTP Request
67 char buf[1024 * 30] = {};
68 read(connection, buf, sizeof(buf));
69
70 // Send HTTP Response
71 const char* response = "HTTP/1.1 200 OK\n\n<h1>AAAAAAAAHELPME</h1>d";
72 write(connection, response, strlen(response));
73
74 shutdown(main_socket, SHUT_RDWR);
75 close(main_socket);
76#endif
77
78 return 0;
79}