]> git.tdb.fi Git - libs/net.git/blobdiff - source/net/socket.cpp
Add a dynamic receiver class for more flexible packet handling
[libs/net.git] / source / net / socket.cpp
index e8e5eaf6275eddb27634a0d473377bed18570d8b..2a1a71c0a4b3aa404b616f09a7be6e1799660c27 100644 (file)
@@ -1,16 +1,17 @@
 #include "platform_api.h"
+#include "socket.h"
 #include <msp/core/systemerror.h>
 #include <msp/io/handle_private.h>
 #include "sockaddr_private.h"
-#include "socket.h"
 #include "socket_private.h"
 
+using namespace std;
+
 namespace Msp {
 namespace Net {
 
 Socket::Socket(const Private &p):
-       priv(new Private),
-       local_addr(0)
+       priv(make_unique<Private>())
 {
        mode = IO::M_RDWR;
 
@@ -18,18 +19,23 @@ Socket::Socket(const Private &p):
 
        SockAddr::SysAddr sa;
        getsockname(priv->handle, reinterpret_cast<sockaddr *>(&sa.addr), &sa.size);
-       local_addr = SockAddr::new_from_sys(sa);
+       local_addr.reset(SockAddr::new_from_sys(sa));
 
        platform_init();
 }
 
 Socket::Socket(Family af, int type, int proto):
-       priv(new Private),
-       local_addr(0)
+       priv(make_unique<Private>())
 {
        mode = IO::M_RDWR;
 
+#ifdef __linux__
+       type |= SOCK_CLOEXEC;
+#endif
        priv->handle = socket(family_to_sys(af), type, proto);
+#ifndef __linux__
+       set_inherit(false);
+#endif
 
        platform_init();
 }
@@ -37,20 +43,26 @@ Socket::Socket(Family af, int type, int proto):
 Socket::~Socket()
 {
        platform_cleanup();
-
-       delete local_addr;
-       delete priv;
 }
 
 void Socket::set_block(bool b)
 {
-       mode = (mode&~IO::M_NONBLOCK);
-       if(b)
-               mode = (mode|IO::M_NONBLOCK);
-
+       IO::adjust_mode(mode, IO::M_NONBLOCK, !b);
        priv->set_block(b);
 }
 
+void Socket::set_inherit(bool i)
+{
+       IO::adjust_mode(mode, IO::M_INHERIT, i);
+       priv->set_inherit(i);
+}
+
+const IO::Handle &Socket::get_handle(IO::Mode)
+{
+       // TODO could this be implemented somehow?
+       throw unsupported("Socket::get_handle");
+}
+
 const IO::Handle &Socket::get_event_handle()
 {
        return priv->event;
@@ -64,13 +76,12 @@ void Socket::bind(const SockAddr &addr)
        if(err==-1)
                throw system_error("bind");
 
-       delete local_addr;
-       local_addr = addr.copy();
+       local_addr.reset(addr.copy());
 }
 
 const SockAddr &Socket::get_local_address() const
 {
-       if(local_addr==0)
+       if(!local_addr)
                throw bad_socket_state("not bound");
        return *local_addr;
 }