]> git.tdb.fi Git - libs/net.git/blob - source/net/socket.cpp
Move most platform-specific code into overlay directories
[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 namespace Msp {
9 namespace Net {
10
11 Socket::Socket(const Private &p):
12         priv(new Private),
13         local_addr(0)
14 {
15         mode = IO::M_RDWR;
16
17         priv->handle = p.handle;
18
19         SockAddr::SysAddr sa;
20         getsockname(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
21         local_addr = SockAddr::new_from_sys(sa);
22
23         platform_init();
24 }
25
26 Socket::Socket(Family af, int type, int proto):
27         priv(new Private),
28         local_addr(0)
29 {
30         mode = IO::M_RDWR;
31
32         priv->handle = socket(family_to_sys(af), type, proto);
33
34         platform_init();
35 }
36
37 Socket::~Socket()
38 {
39         platform_cleanup();
40
41         delete local_addr;
42         delete priv;
43 }
44
45 void Socket::set_block(bool b)
46 {
47         mode = (mode&~IO::M_NONBLOCK);
48         if(b)
49                 mode = (mode|IO::M_NONBLOCK);
50
51         priv->set_block(b);
52 }
53
54 const IO::Handle &Socket::get_event_handle()
55 {
56         return priv->event;
57 }
58
59 void Socket::bind(const SockAddr &addr)
60 {
61         SockAddr::SysAddr sa = addr.to_sys();
62
63         int err = ::bind(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), sa.size);
64         if(err==-1)
65                 throw system_error("bind");
66
67         delete local_addr;
68         local_addr = addr.copy();
69 }
70
71 const SockAddr &Socket::get_local_address() const
72 {
73         if(local_addr==0)
74                 throw bad_socket_state("not bound");
75         return *local_addr;
76 }
77
78 void Socket::set_socket_events(unsigned e)
79 {
80         IO::PollEvent pe = static_cast<IO::PollEvent>(e&4095);
81         if(e&S_CONNECT)
82                 pe = pe|IO::P_OUTPUT;
83         if(e&S_ACCEPT)
84                 pe = pe|IO::P_INPUT;
85
86         set_platform_events(e);
87         set_events(pe);
88 }
89
90 } // namespace Net
91 } // namespace Msp