From 35009eb3f51a6fd0f9261f892a85d97d81e69886 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Mon, 13 Dec 2010 11:09:52 +0000 Subject: [PATCH] Add support for setting socket timeouts --- source/socket.cpp | 25 ++++++++++++++++++++++++- source/socket.h | 4 +++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/source/socket.cpp b/source/socket.cpp index 6db6271..49614df 100644 --- a/source/socket.cpp +++ b/source/socket.cpp @@ -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(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(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(optval), optlen); diff --git a/source/socket.h b/source/socket.h index d807b7d..db4206c 100644 --- a/source/socket.h +++ b/source/socket.h @@ -39,11 +39,13 @@ public: void bind(const SockAddr &); virtual int connect(const SockAddr &) =0; void close(); + void set_timeout(const Time::TimeDelta &); const SockAddr &get_local_address() const; const SockAddr &get_peer_address() const; protected: void check_state(bool) const; - int get_option(int, int, void *, socklen_t *); + int set_option(int, int, const void *, socklen_t); + int get_option(int, int, void *, socklen_t *) const; unsigned do_write(const char *, unsigned); unsigned do_read(char *, unsigned); }; -- 2.45.2