complete tutorial from video
This commit is contained in:
parent
40a4a2d5de
commit
6447ae9831
@ -1,4 +1,9 @@
|
||||
# Minimal Web Server
|
||||
|
||||
```
|
||||
gcc -o main main.c
|
||||
./main
|
||||
```
|
||||
|
||||
Original tutorial: https://www.youtube.com/watch?v=2HrYIl6GpYg
|
||||
|
||||
|
1
index.html
Normal file
1
index.html
Normal file
@ -0,0 +1 @@
|
||||
<h1> Hello, World! </h1>
|
51
main.c
Normal file
51
main.c
Normal file
@ -0,0 +1,51 @@
|
||||
#include <errno.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/sendfile.h>
|
||||
|
||||
int main() {
|
||||
int port = 8080;
|
||||
|
||||
int server_soc = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (server_soc == -1) {
|
||||
printf("ERROR: Failed to open socket: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_in addr = {
|
||||
.sin_family = AF_INET,
|
||||
.sin_port = htons(port),
|
||||
.sin_addr = 0
|
||||
};
|
||||
if (bind(server_soc, (struct sockaddr*)&addr, sizeof(addr))) {
|
||||
printf("ERROR: Failed to bind: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (listen(server_soc, 10)) {
|
||||
printf("ERROR: Failed to listen: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
|
||||
int client_soc = accept(server_soc, NULL, NULL);
|
||||
|
||||
char buffer[256];
|
||||
int byte_count = recv(client_soc, buffer, sizeof(buffer), 0);
|
||||
|
||||
char *filename = buffer + 5;
|
||||
char *space = strchr(filename, ' ');
|
||||
space[0] = 0;
|
||||
|
||||
int file_fd = open(filename, O_RDONLY);
|
||||
sendfile(client_soc, file_fd, 0, 256);
|
||||
close(file_fd);
|
||||
|
||||
close(client_soc);
|
||||
close(server_soc);
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user