-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathsocket.hh
85 lines (64 loc) · 2.19 KB
/
socket.hh
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
#ifndef SOCKET_HH
#define SOCKET_HH
#include <functional>
#include "address.hh"
#include "file_descriptor.hh"
/* class for network sockets (UDP, TCP, etc.) */
class Socket : public FileDescriptor
{
private:
/* get the local or peer address the socket is connected to */
Address get_address( const std::string & name_of_function,
const std::function<int(int, sockaddr *, socklen_t *)> & function ) const;
protected:
/* default constructor */
Socket( const int domain, const int type );
/* construct from file descriptor */
Socket( FileDescriptor && s_fd, const int domain, const int type );
/* set socket option */
template <typename option_type>
void setsockopt( const int level, const int option, const option_type & option_value );
public:
/* bind socket to a specified local address (usually to listen/accept) */
void bind( const Address & address );
/* connect socket to a specified peer address */
void connect( const Address & address );
/* accessors */
Address local_address( void ) const;
Address peer_address( void ) const;
/* allow local address to be reused sooner, at the cost of some robustness */
void set_reuseaddr( void );
};
/* UDP socket */
class UDPSocket : public Socket
{
public:
UDPSocket() : Socket( AF_INET6, SOCK_DGRAM ) {}
struct received_datagram {
Address source_address;
uint64_t timestamp;
std::string payload;
};
/* receive datagram, timestamp, and where it came from */
received_datagram recv( void );
/* send datagram to specified address */
void sendto( const Address & peer, const std::string & payload );
/* send datagram to connected address */
void send( const std::string & payload );
/* turn on timestamps on receipt */
void set_timestamps( void );
};
/* TCP socket */
class TCPSocket : public Socket
{
private:
/* private constructor used by accept() */
TCPSocket( FileDescriptor && fd ) : Socket( std::move( fd ), AF_INET6, SOCK_STREAM ) {}
public:
TCPSocket() : Socket( AF_INET6, SOCK_STREAM ) {}
/* mark the socket as listening for incoming connections */
void listen( const int backlog = 16 );
/* accept a new incoming connection */
TCPSocket accept( void );
};
#endif /* SOCKET_HH */