diff options
author | mrfoxygmfr <mrfoxygmfr@sch9.ru> | 2025-05-20 21:50:25 +0300 |
---|---|---|
committer | mrfoxygmfr <mrfoxygmfr@sch9.ru> | 2025-05-20 21:50:58 +0300 |
commit | 6416c8feecc760807f4edf5d9c8e8be9c2df8981 (patch) | |
tree | 8a8b734e3ab97060c7ed239f6217b5985b7f1189 /lib/net/common.c | |
parent | 78bd565b9c54a962e28ea4865be286b0605ca941 (diff) |
feat(lib/net): network library implemented
Diffstat (limited to 'lib/net/common.c')
-rw-r--r-- | lib/net/common.c | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/lib/net/common.c b/lib/net/common.c new file mode 100644 index 0000000..f85a564 --- /dev/null +++ b/lib/net/common.c @@ -0,0 +1,67 @@ +#include "./common.h" +#include <netdb.h> +#include <netinet/in.h> +#include <stdlib.h> +#include <string.h> + +const uint32_t TCPALIVE_IDLE_TIME = 30; +const uint32_t TCPALIVE_CHECK_INTVL = 10; +const uint32_t TCPALIVE_CHECK_CNT = 5; + +struct sockaddr_in* get_addr(const char* addr, const char* port) { + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = 0; + hints.ai_protocol = 0; + + struct addrinfo* res; + if (getaddrinfo(addr, port, &hints, &res) != 0) { + fprintf(stderr, "[client_create_socket] Unable to call getaddrinfo()\n"); + exit(EXIT_FAILURE); + } + + if (res->ai_next != NULL) { + fprintf(stderr, "[client_create_socket] Ambigous result of getaddrinfo()\n"); + exit(EXIT_FAILURE); + } + + struct sockaddr_in* result = calloc(1, sizeof(*result)); + memcpy(result, res->ai_addr, sizeof(*res->ai_addr)); + + freeaddrinfo(res); + + return result; +} + +void conn_close(conn_t* conn) { + if (close(conn->conn_socket_fd) == -1) { + fprintf(stderr, "[conn_close] Unable to close connection socket\n"); + exit(EXIT_FAILURE); + } +} + +int conn_configure_tcpalive(conn_t* conn) { + int setsockopt_arg = 1; + if (setsockopt(conn->conn_socket_fd, SOL_SOCKET, SO_KEEPALIVE, &setsockopt_arg, sizeof(setsockopt_arg)) == -1) { + return -1; + } + + setsockopt_arg = TCPALIVE_IDLE_TIME; + if (setsockopt(conn->conn_socket_fd, IPPROTO_TCP, TCP_KEEPIDLE, &setsockopt_arg, sizeof(setsockopt_arg)) == -1) { + return -1; + } + + setsockopt_arg = TCPALIVE_CHECK_INTVL; + if (setsockopt(conn->conn_socket_fd, IPPROTO_TCP, TCP_KEEPINTVL, &setsockopt_arg, sizeof(setsockopt_arg)) == -1) { + return -1; + } + + setsockopt_arg = TCPALIVE_CHECK_CNT; + if (setsockopt(conn->conn_socket_fd, IPPROTO_TCP, TCP_KEEPCNT, &setsockopt_arg, sizeof(setsockopt_arg)) == -1) { + return -1; + } + + return 1; +} |