]> git.tdb.fi Git - libs/net.git/blob - source/net/socket.cpp
Add a dynamic receiver class for more flexible packet handling
[libs/net.git] / source / net / socket.cpp
1 #include "platform_api.h"
2 #include "socket.h"
3 #include <msp/core/systemerror.h>
4 #include <msp/io/handle_private.h>
5 #include "sockaddr_private.h"
6 #include "socket_private.h"
7
8 using namespace std;
9
10 namespace Msp {
11 namespace Net {
12
13 Socket::Socket(const Private &p):
14         priv(make_unique<Private>())
15 {
16         mode = IO::M_RDWR;
17
18         priv->handle = p.handle;
19
20         SockAddr::SysAddr sa;
21         getsockname(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
22         local_addr.reset(SockAddr::new_from_sys(sa));
23
24         platform_init();
25 }
26
27 Socket::Socket(Family af, int type, int proto):
28         priv(make_unique<Private>())
29 {
30         mode = IO::M_RDWR;
31
32 #ifdef __linux__
33         type |= SOCK_CLOEXEC;
34 #endif
35         priv->handle = socket(family_to_sys(af), type, proto);
36 #ifndef __linux__
37         set_inherit(false);
38 #endif
39
40         platform_init();
41 }
42
43 Socket::~Socket()
44 {
45         platform_cleanup();
46 }
47
48 void Socket::set_block(bool b)
49 {
50         IO::adjust_mode(mode, IO::M_NONBLOCK, !b);
51         priv->set_block(b);
52 }
53
54 void Socket::set_inherit(bool i)
55 {
56         IO::adjust_mode(mode, IO::M_INHERIT, i);
57         priv->set_inherit(i);
58 }
59
60 const IO::Handle &Socket::get_handle(IO::Mode)
61 {
62         // TODO could this be implemented somehow?
63         throw unsupported("Socket::get_handle");
64 }
65
66 const IO::Handle &Socket::get_event_handle()
67 {
68         return priv->event;
69 }
70
71 void Socket::bind(const SockAddr &addr)
72 {
73         SockAddr::SysAddr sa = addr.to_sys();
74
75         int err = ::bind(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), sa.size);
76         if(err==-1)
77                 throw system_error("bind");
78
79         local_addr.reset(addr.copy());
80 }
81
82 const SockAddr &Socket::get_local_address() const
83 {
84         if(!local_addr)
85                 throw bad_socket_state("not bound");
86         return *local_addr;
87 }
88
89 void Socket::set_socket_events(unsigned e)
90 {
91         IO::PollEvent pe = static_cast<IO::PollEvent>(e&4095);
92         if(e&S_CONNECT)
93                 pe = pe|IO::P_OUTPUT;
94         if(e&S_ACCEPT)
95                 pe = pe|IO::P_INPUT;
96
97         set_platform_events(e);
98         set_events(pe);
99 }
100
101 } // namespace Net
102 } // namespace Msp