7 #include <sys/socket.h>
10 #include <msp/core/systemerror.h>
11 #include <msp/io/handle_private.h>
12 #include <msp/strings/format.h>
13 #include <msp/time/rawtime_private.h>
14 #include <msp/time/units.h>
15 #include "sockaddr_private.h"
17 #include "socket_private.h"
28 int err = WSAStartup(0x0002, &wsa_data);
30 std::cerr<<"Failed to initialize WinSock: "<<err<<'\n';
47 Socket::Socket(const Private &p):
53 priv->handle = p.handle;
56 getsockname(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
57 local_addr = SockAddr::new_from_sys(sa);
60 *priv->event = CreateEvent(0, false, false, 0);
62 *priv->event = priv->handle;
66 Socket::Socket(Family af, int type, int proto):
72 priv->handle = socket(family_to_sys(af), type, proto);
75 *priv->event = CreateEvent(0, false, false, 0);
77 *priv->event = priv->handle;
84 closesocket(priv->handle);
85 CloseHandle(*priv->event);
87 ::close(priv->handle);
94 void Socket::set_block(bool b)
96 mode = (mode&~IO::M_NONBLOCK);
98 mode = (mode|IO::M_NONBLOCK);
102 ioctlsocket(priv->handle, FIONBIO, &flag);
104 int flags = fcntl(priv->handle, F_GETFL);
105 fcntl(priv->handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
109 const IO::Handle &Socket::get_event_handle()
115 void Socket::bind(const SockAddr &addr)
117 SockAddr::SysAddr sa = addr.to_sys();
119 int err = ::bind(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), sa.size);
121 throw system_error("bind");
124 local_addr = addr.copy();
127 const SockAddr &Socket::get_local_address() const
130 throw bad_socket_state("not bound");
134 void Socket::set_timeout(const Time::TimeDelta &timeout)
137 timeval tv = Time::rawtime_to_timeval(timeout.raw());
138 priv->set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
139 priv->set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
141 DWORD msecs = static_cast<DWORD>(timeout/Time::msec);
142 priv->set_option(SOL_SOCKET, SO_RCVTIMEO, &msecs, sizeof(DWORD));
143 priv->set_option(SOL_SOCKET, SO_SNDTIMEO, &msecs, sizeof(DWORD));
148 int Socket::Private::set_option(int level, int optname, const void *optval, socklen_t optlen)
151 return setsockopt(handle, level, optname, reinterpret_cast<const char *>(optval), optlen);
153 return setsockopt(handle, level, optname, optval, optlen);
157 int Socket::Private::get_option(int level, int optname, void *optval, socklen_t *optlen)
160 return getsockopt(handle, level, optname, reinterpret_cast<char *>(optval), optlen);
162 return getsockopt(handle, level, optname, optval, optlen);