]> git.tdb.fi Git - libs/net.git/blobdiff - source/socket.cpp
Add support for setting socket timeouts
[libs/net.git] / source / socket.cpp
index 6db6271a8a2710b01588a7ac9de4fa363cbe1727..49614df0c807bdf89f3d5772b3afb996b1bf0039 100644 (file)
@@ -144,6 +144,20 @@ void Socket::close()
        peer_addr=0;
 }
 
+void Socket::set_timeout(const Time::TimeDelta &timeout)
+{
+#ifndef WIN32
+       timeval tv;
+       timeout.fill_timeval(tv);
+       set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
+       set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
+#else
+       DWORD msecs = static_cast<DWORD>(timeout/Time::msec);
+       set_option(SOL_SOCKET, SO_RCVTIMEO, &msecs, sizeof(DWORD));
+       set_option(SOL_SOCKET, SO_SNDTIMEO, &msecs, sizeof(DWORD));
+#endif
+}
+
 const SockAddr &Socket::get_local_address() const
 {
        if(local_addr==0)
@@ -166,7 +180,16 @@ void Socket::check_state(bool conn) const
                throw Exception("Socket is not connected");
 }
 
-int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen)
+int Socket::set_option(int level, int optname, const void *optval, socklen_t optlen)
+{
+#ifdef WIN32
+       return setsockopt(handle, level, optname, reinterpret_cast<const char *>(optval), optlen);
+#else
+       return setsockopt(handle, level, optname, optval, optlen);
+#endif
+}
+
+int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen) const
 {
 #ifdef WIN32
        return getsockopt(handle, level, optname, reinterpret_cast<char *>(optval), optlen);