4 #include <sys/socket.h>
7 #include <msp/core/systemerror.h>
8 #include <msp/io/handle_private.h>
9 #include <msp/strings/format.h>
10 #include <msp/time/rawtime_private.h>
11 #include <msp/time/units.h>
12 #include "sockaddr_private.h"
14 #include "socket_private.h"
25 int err = WSAStartup(0x0002, &wsa_data);
27 std::cerr<<"Failed to initialize WinSock: "<<err<<'\n';
44 Socket::Socket(const Private &p):
48 priv->handle = p.handle;
51 getsockname(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
52 local_addr = SockAddr::new_from_sys(sa);
55 *priv->event = CreateEvent(0, false, false, 0);
57 *priv->event = priv->handle;
61 Socket::Socket(Family af, int type, int proto):
65 priv->handle = socket(family_to_sys(af), type, proto);
68 *priv->event = CreateEvent(0, false, false, 0);
70 *priv->event = priv->handle;
77 closesocket(priv->handle);
78 CloseHandle(*priv->event);
80 ::close(priv->handle);
87 void Socket::set_block(bool b)
89 mode = (mode&~IO::M_NONBLOCK);
91 mode = (mode|IO::M_NONBLOCK);
95 ioctlsocket(priv->handle, FIONBIO, &flag);
97 int flags = fcntl(priv->handle, F_GETFL);
98 fcntl(priv->handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
102 const IO::Handle &Socket::get_event_handle()
108 void Socket::bind(const SockAddr &addr)
110 SockAddr::SysAddr sa = addr.to_sys();
112 int err = ::bind(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), sa.size);
114 throw system_error("bind");
117 local_addr = addr.copy();
120 const SockAddr &Socket::get_local_address() const
123 throw bad_socket_state("not bound");
127 void Socket::set_timeout(const Time::TimeDelta &timeout)
130 timeval tv = Time::rawtime_to_timeval(timeout.raw());
131 set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
132 set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
134 DWORD msecs = static_cast<DWORD>(timeout/Time::msec);
135 set_option(SOL_SOCKET, SO_RCVTIMEO, &msecs, sizeof(DWORD));
136 set_option(SOL_SOCKET, SO_SNDTIMEO, &msecs, sizeof(DWORD));
140 int Socket::set_option(int level, int optname, const void *optval, socklen_t optlen)
143 return setsockopt(priv->handle, level, optname, reinterpret_cast<const char *>(optval), optlen);
145 return setsockopt(priv->handle, level, optname, optval, optlen);
149 int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen) const
152 return getsockopt(priv->handle, level, optname, reinterpret_cast<char *>(optval), optlen);
154 return getsockopt(priv->handle, level, optname, optval, optlen);