]> git.tdb.fi Git - libs/net.git/blob - source/net/socket.cpp
877c1da2b99a31d586b9f5832717411cee96d625
[libs/net.git] / source / net / socket.cpp
1 #include "platform_api.h"
2 #include <msp/core/systemerror.h>
3 #include <msp/io/handle_private.h>
4 #include "sockaddr_private.h"
5 #include "socket.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         // TODO use SOCK_CLOEXEC on Linux
33         priv->handle = socket(family_to_sys(af), type, proto);
34
35         platform_init();
36 }
37
38 Socket::~Socket()
39 {
40         platform_cleanup();
41 }
42
43 void Socket::set_block(bool b)
44 {
45         IO::adjust_mode(mode, IO::M_NONBLOCK, !b);
46         priv->set_block(b);
47 }
48
49 void Socket::set_inherit(bool i)
50 {
51         IO::adjust_mode(mode, IO::M_INHERIT, i);
52         priv->set_inherit(i);
53 }
54
55 const IO::Handle &Socket::get_handle(IO::Mode)
56 {
57         // TODO could this be implemented somehow?
58         throw unsupported("Socket::get_handle");
59 }
60
61 const IO::Handle &Socket::get_event_handle()
62 {
63         return priv->event;
64 }
65
66 void Socket::bind(const SockAddr &addr)
67 {
68         SockAddr::SysAddr sa = addr.to_sys();
69
70         int err = ::bind(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), sa.size);
71         if(err==-1)
72                 throw system_error("bind");
73
74         local_addr.reset(addr.copy());
75 }
76
77 const SockAddr &Socket::get_local_address() const
78 {
79         if(!local_addr)
80                 throw bad_socket_state("not bound");
81         return *local_addr;
82 }
83
84 void Socket::set_socket_events(unsigned e)
85 {
86         IO::PollEvent pe = static_cast<IO::PollEvent>(e&4095);
87         if(e&S_CONNECT)
88                 pe = pe|IO::P_OUTPUT;
89         if(e&S_ACCEPT)
90                 pe = pe|IO::P_INPUT;
91
92         set_platform_events(e);
93         set_events(pe);
94 }
95
96 } // namespace Net
97 } // namespace Msp