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>
23 int err = WSAStartup(0x0002, &wsa_data);
25 std::cerr<<"Failed to initialize WinSock: "<<err<<'\n';
42 Socket::Socket(SocketHandle h, const SockAddr &paddr):
46 peer_addr(paddr.copy())
49 socklen_t size = sizeof(sockaddr_storage);
50 getsockname(handle, reinterpret_cast<sockaddr *>(&sa), &size);
51 local_addr = SockAddr::create(sa);
54 event = CreateEvent(0, false, false, 0);
60 Socket::Socket(Family af, int type, int proto):
65 handle = socket(af, type, proto);
68 event = CreateEvent(0, false, false, 0);
76 signal_flush_required.emit();
88 void Socket::set_block(bool b)
90 mode = (mode&~IO::M_NONBLOCK);
92 mode = (mode|IO::M_NONBLOCK);
96 ioctlsocket(handle, FIONBIO, &flag);
98 int flags = fcntl(handle, F_GETFL);
99 fcntl(handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
103 const IO::Handle &Socket::get_event_handle()
109 void Socket::bind(const SockAddr &addr)
114 unsigned size = addr.fill_sockaddr(sa);
116 int err = ::bind(handle, reinterpret_cast<sockaddr *>(&sa), size);
118 throw system_error("bind");
121 local_addr = addr.copy();
124 void Socket::set_timeout(const Time::TimeDelta &timeout)
127 timeval tv = Time::rawtime_to_timeval(timeout.raw());
128 set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
129 set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
131 DWORD msecs = static_cast<DWORD>(timeout/Time::msec);
132 set_option(SOL_SOCKET, SO_RCVTIMEO, &msecs, sizeof(DWORD));
133 set_option(SOL_SOCKET, SO_SNDTIMEO, &msecs, sizeof(DWORD));
137 const SockAddr &Socket::get_local_address() const
140 throw bad_socket_state("not bound");
144 const SockAddr &Socket::get_peer_address() const
147 throw bad_socket_state("not connected");
151 void Socket::check_state(bool conn) const
153 if(conn && !connected)
154 throw bad_socket_state("not connected");
157 int Socket::set_option(int level, int optname, const void *optval, socklen_t optlen)
160 return setsockopt(handle, level, optname, reinterpret_cast<const char *>(optval), optlen);
162 return setsockopt(handle, level, optname, optval, optlen);
166 int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen) const
169 return getsockopt(handle, level, optname, reinterpret_cast<char *>(optval), optlen);
171 return getsockopt(handle, level, optname, optval, optlen);
175 unsigned Socket::do_write(const char *buf, unsigned size)
182 int ret = ::send(handle, buf, size, 0);
188 throw system_error("send");
194 unsigned Socket::do_read(char *buf, unsigned size)
201 int ret = ::recv(handle, buf, size, 0);
207 throw system_error("recv");
209 else if(ret==0 && !eof_flag)
212 signal_end_of_file.emit();
213 set_events(IO::P_NONE);