-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
80 lines (66 loc) · 1.81 KB
/
server.c
File metadata and controls
80 lines (66 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/sendfile.h>
#define PORT 5050
#define BACKLOG 1
#define BUFF_SIZE 256
int main(void) {
int server_fd = socket(AF_INET,SOCK_STREAM,0);
if(server_fd == -1) {
perror("socket()");
return 1;
}
struct sockaddr_in address = {
AF_INET,
htons(PORT),
INADDR_ANY,
};
int addrlength = sizeof(address);
if(bind(server_fd,(struct sockaddr*)&address,(socklen_t)addrlength)==-1) {
perror("bind()");
close(server_fd);
return 1;
}
if(listen(server_fd,BACKLOG)==-1) {
perror("listen()");
close(server_fd);
return 1;
}
printf("Server is now listening on port 5050...\n");
int client_fd = accept(server_fd,0,0);
if(client_fd == -1) {
perror("accept()");
close(server_fd);
return 1;
}
char buffer[BUFF_SIZE];
if(recv(client_fd,buffer,BUFF_SIZE,0)==-1) {
perror("recv()");
close(client_fd);
close(server_fd);
return 1;
}
char *filename = buffer;
filename += 5; //skips the first 5 characters, that means that is going to skip the GET / so we can get the filename
*(strchr(filename,' ')) = '\0'; //this line of code finds the first whitespace and puts a null terminator there so we can keep the filename only
int file_fd = open(filename,O_RDONLY,0);
if(file_fd == -1) {
perror("open()");
close(client_fd);
close(server_fd);
return 1;
}
if(sendfile(client_fd,file_fd,0,BUFF_SIZE)==-1) {
perror("sendfile()");
close(client_fd);
close(server_fd);
return 1;
}
close(client_fd);
close(server_fd);
return 0;
}