-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathServerSocket.h
executable file
·112 lines (93 loc) · 2.79 KB
/
ServerSocket.h
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
107
108
109
110
111
112
// Definition of the ServerSocket class
#ifndef SERVERSOCKET_H
#define SERVERSOCKET_H
#if defined(unix) || defined(__unix__) || defined(__unix) || defined(__APPLE__)
#include "Socket.h"
#include "SocketException.h"
#include "myconverters.h"
#include <arpa/inet.h>
#include <errno.h>
#include <openssl/ossl_typ.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <iostream>
#include <string>
#include <list>
#include <sys/socket.h>
class ServerSocket : public Socket {
public:
class Connection : public Socket {
public:
Connection(ServerSocket* serverSocket, SSL *cSSL)
: serverSocket(serverSocket), cSSL(cSSL)
{
m_sock = serverSocket->Socket::accept(&this->m_addr, & * this->cSSL,
serverSocket->socketType);
if (m_sock <= 0) {
throw SocketException("Could not respond to new connection");
}
//serverSocket->incomingConnections.push_back(*this);
}
~Connection() {
close(this->m_sock);
}
bool operator<<(const std::string& s) const {
if (!send(s)) {
throw SocketException("Could not write to socket.");
}
return true;
};
bool operator>>(std::string& s) const {
if ((int) this->recv(s, this->MAXRECV) <= 0) {
throw SocketException("Could not read from socket.");
}
return true;
};
void *get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET)
return &(((struct sockaddr_in*) sa)->sin_addr);
return &(((struct sockaddr_in6*) sa)->sin6_addr);
}
std::string getDestinationIP() {
char s[INET6_ADDRSTRLEN];
inet_ntop(AF_INET, get_in_addr(&m_addr), s, sizeof s);
return std::string(s);
}
std::string getDestinationPort() {
return "";
}
std::string getSourcePort() {
int port = getPort(connectionDescriptor);
return std::string(itoa(port));
}
private:
int connectionDescriptor = -1;
SSL *cSSL;
sockaddr m_addr;
ServerSocket * serverSocket;
};
std::list<Connection> incomingConnections;
SOCKET_TYPE socketType;
ServerSocket(int port, SOCKET_TYPE socketType = SOCKET_TYPE::DEFAULT) {
if (!this->create(0)) {
throw SocketException("Could not create server socket.");
}
if (!this->bind(port)) {
throw SocketException("Could not bind to port.");
}
if (!this->listen()) {
throw SocketException("Could not listen to socket.");
}
this->socketType = socketType;
};
ServerSocket() {
};
~ServerSocket() {
};
Connection* accept() {
return new Connection(this, NULL);
}
private:
};
#endif
#endif