summaryrefslogtreecommitdiffstats
path: root/lib/net/common.c
blob: f85a564ecff42c440d5c9adecb8048faf3e9f795 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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;
}