]> git.tdb.fi Git - libs/net.git/blob - source/net/unix/socket.cpp
Add a dynamic receiver class for more flexible packet handling
[libs/net.git] / source / net / unix / socket.cpp
1 #include "platform_api.h"
2 #include "socket.h"
3 #include <cerrno>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <msp/core/systemerror.h>
7 #include <msp/io/handle_private.h>
8 #include <msp/time/rawtime_private.h>
9 #include "sockaddr_private.h"
10 #include "socket_private.h"
11
12 using namespace std;
13
14 namespace Msp {
15 namespace Net {
16
17 void Socket::platform_init()
18 {
19         *priv->event = priv->handle;
20         set_inherit(false);
21 }
22
23 void Socket::platform_cleanup()
24 {
25         close(priv->handle);
26 }
27
28 void Socket::set_timeout(const Time::TimeDelta &timeout)
29 {
30         timeval tv = Time::rawtime_to_timeval(timeout.raw());
31         priv->set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
32         priv->set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
33 }
34
35 void Socket::set_platform_events(unsigned)
36 {
37 }
38
39
40 void Socket::Private::set_block(bool b)
41 {
42         int flags = fcntl(handle, F_GETFL);
43         fcntl(handle, F_SETFL, (flags&~O_NONBLOCK)|(b?0:O_NONBLOCK));
44 }
45
46 void Socket::Private::set_inherit(bool i)
47 {
48         int flags = fcntl(handle, F_GETFD);
49         fcntl(handle, F_SETFD, (flags&~O_CLOEXEC)|(i?0:O_CLOEXEC));
50 }
51
52 int Socket::Private::set_option(int level, int optname, const void *optval, socklen_t optlen)
53 {
54         return setsockopt(handle, level, optname, optval, optlen);
55 }
56
57 int Socket::Private::get_option(int level, int optname, void *optval, socklen_t *optlen)
58 {
59         return getsockopt(handle, level, optname, optval, optlen);
60 }
61
62
63 size_t check_sys_error(make_signed<size_t>::type ret, const char *func)
64 {
65         if(ret<0)
66         {
67                 if(errno==EAGAIN || errno==EWOULDBLOCK)
68                         return 0;
69                 else
70                         throw system_error(func);
71         }
72
73         return ret;
74 }
75
76 bool check_sys_connect_error(int ret)
77 {
78         if(ret<0)
79         {
80                 if(errno==EINPROGRESS)
81                         return false;
82                 else
83                         throw system_error("connect");
84         }
85
86         return true;
87 }
88
89 } // namespace Net
90 } // namespace Msp