3 This file is part of libmspnet
4 Copyright © 2008 Mikkosoft Productions, Mikko Rasa
5 Distributed under the LGPL
11 #include <sys/socket.h>
14 #include <msp/strings/formatter.h>
15 #include <msp/time/units.h>
27 int err=WSAStartup(0x0002, &wsa_data);
29 std::cerr<<"Failed to initialize WinSock: "<<err<<'\n';
46 void Socket::set_block(bool b)
48 mode=(mode&~IO::M_NONBLOCK);
50 mode=(mode|IO::M_NONBLOCK);
54 ioctlsocket(handle, FIONBIO, &flag);
56 int flags=fcntl(handle, F_GETFL);
57 fcntl(handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
61 IO::Handle Socket::get_event_handle()
71 void Socket::bind(const SockAddr &addr)
76 unsigned size=addr.fill_sockaddr(sa);
78 int err=::bind(handle, &sa, size);
80 throw SystemError("Unable to bind", errno);
83 local_addr=addr.copy();
87 Closes the socket. Most operations on the socket will return an error after
92 if(handle==MSP_NET_INVALID_SOCKET_HANDLE)
95 set_events(IO::P_NONE);
97 signal_flush_required.emit();
104 handle=MSP_NET_INVALID_SOCKET_HANDLE;
105 signal_closed.emit();
113 const SockAddr &Socket::get_local_address() const
116 throw InvalidState("Local address not set");
120 const SockAddr &Socket::get_peer_address() const
123 throw InvalidState("Peer address not set");
132 Socket::Socket(SocketHandle h, const SockAddr &paddr):
136 peer_addr(paddr.copy())
139 socklen_t size=sizeof(sockaddr);
140 getsockname(handle, &sa, &size);
141 local_addr=SockAddr::create(sa);
144 event=CreateEvent(0, false, false, 0);
148 Socket::Socket(Family af, int type, int proto):
153 handle=socket(af, type, proto);
156 event=CreateEvent(0, false, false, 0);
160 void Socket::check_state(bool conn) const
162 if(handle==MSP_NET_INVALID_SOCKET_HANDLE)
163 throw Exception("Socket is closed");
164 if(conn && !connected)
165 throw Exception("Socket is not connected");
168 int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen)
171 return getsockopt(handle, level, optname, reinterpret_cast<char *>(optval), optlen);
173 return getsockopt(handle, level, optname, optval, optlen);
177 unsigned Socket::do_write(const char *buf, unsigned size)
184 int ret=::send(handle, buf, size, 0);
190 throw SystemError("Writing to socket failed", errno);
196 unsigned Socket::do_read(char *buf, unsigned size)
203 int ret=::recv(handle, buf, size, 0);
209 throw SystemError("Reading from socket failed", errno);
211 else if(ret==0 && !eof_flag)
214 signal_end_of_file.emit();
215 set_events(IO::P_NONE);