From 22ddb088cdf8b59442d4e6504331644e768b800d Mon Sep 17 00:00:00 2001 From: Marc Schink Date: Wed, 12 Aug 2020 01:33:09 +0200 Subject: socket: Add function to set blocking mode Signed-off-by: Marc Schink --- libjaylink/libjaylink-internal.h | 1 + libjaylink/socket.c | 41 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/libjaylink/libjaylink-internal.h b/libjaylink/libjaylink-internal.h index 2a053f0..0952998 100644 --- a/libjaylink/libjaylink-internal.h +++ b/libjaylink/libjaylink-internal.h @@ -271,6 +271,7 @@ JAYLINK_PRIV bool socket_get_option(int sock, int level, int option, void *value, size_t *length); JAYLINK_PRIV bool socket_set_option(int sock, int level, int option, const void *value, size_t length); +JAYLINK_PRIV bool socket_set_blocking(int sock, bool blocking); /*--- transport.c -----------------------------------------------------------*/ diff --git a/libjaylink/socket.c b/libjaylink/socket.c index f40390e..9586e0c 100644 --- a/libjaylink/socket.c +++ b/libjaylink/socket.c @@ -23,6 +23,7 @@ #include #include #include +#include #endif #include "libjaylink.h" @@ -275,3 +276,43 @@ JAYLINK_PRIV bool socket_set_option(int sock, int level, int option, return false; } + +/** + * Set the blocking mode of a socket. + * + * @param[in] sock Socket descriptor. + * @param[in] blocking Blocking mode. + * + * @return Whether the blocking mode was set successfully. + */ +JAYLINK_PRIV bool socket_set_blocking(int sock, bool blocking) +{ + int ret; +#ifdef _WIN32 + u_long mode; + + mode = !blocking; + ret = ioctlsocket(sock, FIONBIO, &mode); + + if (ret != NO_ERROR) + return false; +#else + int flags; + + flags = fcntl(sock, F_GETFL, 0); + + if (flags < 0) + return false; + + if (blocking) + flags &= ~O_NONBLOCK; + else + flags |= O_NONBLOCK; + + ret = fcntl(sock, F_SETFL, flags); + + if (ret != 0) + return false; +#endif + return true; +} -- cgit v1.1