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 Socket::Socket(SocketHandle h, const SockAddr &paddr):
50 peer_addr(paddr.copy())
53 socklen_t size=sizeof(sockaddr);
54 getsockname(handle, &sa, &size);
55 local_addr=SockAddr::create(sa);
58 event=CreateEvent(0, false, false, 0);
62 Socket::Socket(Family af, int type, int proto):
67 handle=socket(af, type, proto);
70 event=CreateEvent(0, false, false, 0);
79 void Socket::set_block(bool b)
81 mode=(mode&~IO::M_NONBLOCK);
83 mode=(mode|IO::M_NONBLOCK);
87 ioctlsocket(handle, FIONBIO, &flag);
89 int flags=fcntl(handle, F_GETFL);
90 fcntl(handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
94 IO::Handle Socket::get_event_handle()
104 void Socket::bind(const SockAddr &addr)
109 unsigned size=addr.fill_sockaddr(sa);
111 int err=::bind(handle, &sa, size);
113 throw SystemError("Unable to bind", errno);
116 local_addr=addr.copy();
120 Closes the socket. Most operations on the socket will throw an exception after
125 if(handle==MSP_NET_INVALID_SOCKET_HANDLE)
128 set_events(IO::P_NONE);
130 signal_flush_required.emit();
137 handle=MSP_NET_INVALID_SOCKET_HANDLE;
138 signal_closed.emit();
146 const SockAddr &Socket::get_local_address() const
149 throw InvalidState("Local address not set");
153 const SockAddr &Socket::get_peer_address() const
156 throw InvalidState("Peer address not set");
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);