-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFTPServer.cpp
More file actions
106 lines (73 loc) · 2.39 KB
/
FTPServer.cpp
File metadata and controls
106 lines (73 loc) · 2.39 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//****************************************************************************
// REDES Y SISTEMAS DISTRIBUIDOS
//
// 2ª de grado de Ingeniería Informática
//
// Main class of the FTP server
// DAVID FERNANDO REDONDO DURAND
// alu0100851700@ull.edu.es
//
//****************************************************************************
#include <cerrno>
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <list>
#include "common.h"
#include "FTPServer.h"
#include "ClientConnection.h"
int define_socket_TCP(int port) {
struct sockaddr_in sin;
int msock = socket(AF_INET,SOCK_STREAM, 0);
if(msock < 0) {
errexit("No puedo crear el socket: %s\n", strerror(errno));
}
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
if(bind(msock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
errexit("No puedo hacer el bind con el puerto: %s\n", strerror(errno));
}
if (listen(msock, 5) < 0)
errexit("Fallo en el listen: %s\n", strerror(errno));
return msock;
}
// This function is executed when the thread is executed.
void* run_client_connection(void *c) {
ClientConnection *connection = (ClientConnection *)c;
connection->WaitForRequests();
return NULL;
}
FTPServer::FTPServer(int port) {
this->port = port;
}
// Parada del servidor.
void FTPServer::stop() {
close(msock);
shutdown(msock, SHUT_RDWR);
}
// Starting of the server
void FTPServer::run() {
struct sockaddr_in fsin;
int ssock;
socklen_t alen;
msock = define_socket_TCP(port); // This function must be implemented by you.
while (1) {
pthread_t thread;
ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
if(ssock < 0)
errexit("Fallo en el accept: %s\n", strerror(errno));
ClientConnection *connection = new ClientConnection(ssock, fsin.sin_addr.s_addr);
// Here a thread is created in order to process multiple
// requests simultaneously
pthread_create(&thread, NULL, run_client_connection, (void*)connection);
}
}