2 * @brief Socket handling utilities.
4 /* Copyright (C) 2006,2007,2008,2015 Olly Betts
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "socket_utils.h"
27 #include "safesyssocket.h"
33 # include "msvcignoreinvalidparam.h"
36 /// Convert an fd (which might be a socket) to a WIN32 HANDLE.
37 extern HANDLE
fd_to_handle(int fd
) {
38 MSVCIgnoreInvalidParameter invalid_handle_value_is_ok
;
39 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
40 if (handle
!= INVALID_HANDLE_VALUE
) return handle
;
41 // On WIN32, a socket fd isn't the same as a non-socket fd - in fact it's
43 return reinterpret_cast<HANDLE
>(fd
);
46 /// Close an fd, which might be a socket.
47 extern void close_fd_or_socket(int fd
) {
48 MSVCIgnoreInvalidParameter invalid_fd_value_is_ok
;
49 if (close(fd
) == -1 && errno
== EBADF
) {
50 // Bad file descriptor - probably because the fd is actually
59 set_socket_timeouts(int fd
, double timeout
)
63 #if defined SO_SNDTIMEO || defined SO_RCVTIMEO
67 RealTime::to_timeval(timeout
, &t
);
69 // Just to be different, it's a DWORD counting in milliseconds.
71 if (usual(timeout
< numeric_limits
<DWORD
>::max() / 1000))
74 t
= numeric_limits
<DWORD
>::max();
77 (void)setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
,
78 reinterpret_cast<char*>(&t
), sizeof(t
));
81 (void)setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
,
82 reinterpret_cast<char*>(&t
), sizeof(t
));
87 // SO_SNDTIMEO and SO_RCVTIMEO may be ignored even if they exist, so set
88 // SO_KEEPALIVE anyway if it exists, as it will cause stuck connections to
89 // time out eventually (though it may take ~2 hours).
96 (void)setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
,
97 reinterpret_cast<char*>(&flag
), sizeof(flag
));