-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp-socket.cc
55 lines (44 loc) · 1.43 KB
/
tcp-socket.cc
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
/**
* \author: Rafal Banas
*/
#include "tcp-socket.h"
#include <arpa/inet.h>
#include <memory>
using namespace std;
TcpListener::TcpListener(uint16_t port, int queue_length): port(port) {
sock_fd = socket(PF_INET, SOCK_STREAM, 0);
if (sock_fd < 0) {
throw SocketException("Error in socket(...)");
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(port);
if (bind(sock_fd, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
throw SocketException("Error in bind(...)");
}
if (listen(sock_fd, queue_length) < 0) {
throw SocketException("Error in listen(...)");
}
}
std::shared_ptr<TcpStream> TcpListener::acceptClient() {
struct sockaddr_in client_address;
socklen_t client_address_len = sizeof(client_address);
int incoming_sock_fd = accept(sock_fd, (struct sockaddr *) &client_address, &client_address_len);
if (incoming_sock_fd < 0) {
throw SocketException("Error in accept(...)");
}
return std::shared_ptr<TcpStream>(new TcpStream(incoming_sock_fd, client_address, TCP_BUFFER_SIZE));
}
std::string TcpStream::ip() {
return std::string(inet_ntoa(client_address.sin_addr));
}
TcpListener::~TcpListener() noexcept {
close(sock_fd);
}
TcpStream::~TcpStream() noexcept {
if (in_fd >= 0)
close(in_fd);
}
void TcpStream::inactivate() {
in_fd = -1;
}