]> git.tdb.fi Git - libs/net.git/blob - source/streamlistensocket.cpp
Add netcat example
[libs/net.git] / source / streamlistensocket.cpp
1 #include <cerrno>
2 #include <msp/core/refptr.h>
3 #include <msp/core/systemerror.h>
4 #include <msp/io/handle_private.h>
5 #include <msp/strings/format.h>
6 #include "sockaddr_private.h"
7 #include "socket_private.h"
8 #include "streamlistensocket.h"
9 #include "streamsocket.h"
10
11 using namespace std;
12
13 namespace Msp {
14 namespace Net {
15
16 StreamListenSocket::StreamListenSocket(Family af, int proto):
17         Socket(af, SOCK_STREAM, proto),
18         listening(false)
19 { }
20
21 int StreamListenSocket::connect(const SockAddr &)
22 {
23         // XXX This function needs to go away
24         throw logic_error("Can't connect a listen socket");
25 }
26
27 void StreamListenSocket::listen(const SockAddr &addr, unsigned backlog)
28 {
29         bind(addr);
30
31         int err = ::listen(priv->handle, backlog);
32         if(err==-1)
33                 throw system_error("listen");
34
35 #ifdef WIN32
36         WSAEventSelect(priv->handle, *priv->event, FD_ACCEPT);
37 #endif
38         set_events(IO::P_INPUT);
39
40         listening = true;
41 }
42
43 StreamSocket *StreamListenSocket::accept()
44 {
45         if(!listening)
46                 throw bad_socket_state("not listening");
47
48         SockAddr::SysAddr sa;
49         Private new_p;
50         new_p.handle = ::accept(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
51
52         RefPtr<SockAddr> paddr = SockAddr::from_sys(sa);
53         return new StreamSocket(new_p, *paddr);
54 }
55
56 } // namespace Net
57 } // namespace Msp