-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.cpp
More file actions
85 lines (70 loc) · 1.78 KB
/
socket.cpp
File metadata and controls
85 lines (70 loc) · 1.78 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
#include "socket.hpp"
#include <sys/socket.h>
#include <netinet/in.h> // Internet Protocol
#include <sys/un.h> // Unix sockets
#include <arpa/inet.h> // Manipulating IP addresses
#include <unistd.h> // close()
#include <cerrno>
#include <cstring>
#include <algorithm>
#include "logger.hpp"
extern Log main_log;
Socket::Socket(int domain, int type, int protocol)
: fd(socket(domain,type,protocol))
{
if (fd == -1) { // The socket failed to open
main_log << ERROR << "Socket failed to open: " << strerror(errno) << '\n';
throw errno; // TODO: better exception
}
}
Socket::Socket(int fd)
: fd(fd)
{}
Socket::Socket(Socket&& s)
: fd(0)
{
std::swap(fd,s.fd);
}
Socket::~Socket()
{
if (fd) while (close(fd) && errno != EBADF); // If the file descriptor is valid,
// try to close it
}
void Socket::bind(const SocketAddress& sa)
{
if (::bind(fd,sa.address,sa.length)) {
main_log << ERROR << "Socket failed to bind: " << strerror(errno) << '\n';
throw errno; // TODO: better exception
}
}
void Socket::listen(int backlog)
{
if (::listen(fd,backlog)) {
main_log << ERROR << "Failed to listen on socket: " << strerror(errno) << '\n';
throw errno; // TODO: better exception
}
}
Socket Socket::accept(SocketAddress& sa)
{
int new_fd = ::accept(fd,sa.address,&sa.length);
if (new_fd == -1) {
main_log << ERROR << "Failed to accept on socket: " << strerror(errno) << '\n';
throw errno; // TODO: etc
}
return Socket(new_fd);
}
void Socket::connect(const SocketAddress& sa)
{
if (::connect(fd,sa.address,sa.length)) {
main_log << ERROR << "Failed to connect to socket: " << strerror(errno) << '\n';
throw errno; // TODO: etc
}
}
int Socket::getfd() const
{
return fd;
}
int Socket::write(const void * buffer, ssize_t length)
{
return ::write(fd,buffer,length);
}