5 #include <sys/socket.h>
8 #include <msp/core/systemerror.h>
9 #include <msp/io/handle_private.h>
10 #include <msp/strings/format.h>
11 #include <msp/time/rawtime_private.h>
12 #include <msp/time/units.h>
13 #include "sockaddr_private.h"
15 #include "socket_private.h"
26 int err = WSAStartup(0x0002, &wsa_data);
28 std::cerr<<"Failed to initialize WinSock: "<<err<<'\n';
45 Socket::Socket(const Private &p):
51 priv->handle = p.handle;
54 getsockname(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
55 local_addr = SockAddr::new_from_sys(sa);
58 *priv->event = CreateEvent(0, false, false, 0);
60 *priv->event = priv->handle;
64 Socket::Socket(Family af, int type, int proto):
70 priv->handle = socket(family_to_sys(af), type, proto);
73 *priv->event = CreateEvent(0, false, false, 0);
75 *priv->event = priv->handle;
82 closesocket(priv->handle);
83 CloseHandle(*priv->event);
85 ::close(priv->handle);
92 void Socket::set_block(bool b)
94 mode = (mode&~IO::M_NONBLOCK);
96 mode = (mode|IO::M_NONBLOCK);
100 ioctlsocket(priv->handle, FIONBIO, &flag);
102 int flags = fcntl(priv->handle, F_GETFL);
103 fcntl(priv->handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
107 const IO::Handle &Socket::get_event_handle()
113 void Socket::bind(const SockAddr &addr)
115 SockAddr::SysAddr sa = addr.to_sys();
117 int err = ::bind(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), sa.size);
119 throw system_error("bind");
122 local_addr = addr.copy();
125 const SockAddr &Socket::get_local_address() const
128 throw bad_socket_state("not bound");
132 void Socket::set_timeout(const Time::TimeDelta &timeout)
135 timeval tv = Time::rawtime_to_timeval(timeout.raw());
136 priv->set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
137 priv->set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
139 DWORD msecs = static_cast<DWORD>(timeout/Time::msec);
140 priv->set_option(SOL_SOCKET, SO_RCVTIMEO, &msecs, sizeof(DWORD));
141 priv->set_option(SOL_SOCKET, SO_SNDTIMEO, &msecs, sizeof(DWORD));
146 int Socket::Private::set_option(int level, int optname, const void *optval, socklen_t optlen)
149 return setsockopt(handle, level, optname, reinterpret_cast<const char *>(optval), optlen);
151 return setsockopt(handle, level, optname, optval, optlen);
155 int Socket::Private::get_option(int level, int optname, void *optval, socklen_t *optlen)
158 return getsockopt(handle, level, optname, reinterpret_cast<char *>(optval), optlen);
160 return getsockopt(handle, level, optname, optval, optlen);