aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/net/socket_options.cpp
blob: 29e20362a01391c54040ad4f46184b45fc35b5b2 (plain) (blame)
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
68
69
70
71
72
73
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "socket_options.h"

#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

namespace vespalib {

namespace {

bool set_bool_opt(int fd, int level, int name, bool value) {
    int data = value;
    return (setsockopt(fd, level, name, &data, sizeof(data)) == 0);
}

} // namespace vespalib::<unnamed>

bool
SocketOptions::set_blocking(int fd, bool value)
{
    int flags = fcntl(fd, F_GETFL, NULL);
    if (flags != -1) {
        if (value) {
            flags &= ~O_NONBLOCK; // clear non-blocking flag
        } else {
            flags |= O_NONBLOCK; // set non-blocking flag
        }
        return (fcntl(fd, F_SETFL, flags) == 0);
    }
    return false;
}

bool
SocketOptions::set_nodelay(int fd, bool value)
{
    return set_bool_opt(fd, IPPROTO_TCP, TCP_NODELAY, value);
}

bool
SocketOptions::set_reuse_addr(int fd, bool value)
{
    return set_bool_opt(fd, SOL_SOCKET, SO_REUSEADDR, value);
}

bool
SocketOptions::set_ipv6_only(int fd, bool value)
{
    return set_bool_opt(fd, IPPROTO_IPV6, IPV6_V6ONLY, value);
}

bool
SocketOptions::set_keepalive(int fd, bool value)
{
    return set_bool_opt(fd, SOL_SOCKET, SO_KEEPALIVE, value);
}

bool
SocketOptions::set_linger(int fd, bool enable, int value)
{
    struct linger data;
    memset(&data, 0, sizeof(data));
    data.l_onoff = enable;
    data.l_linger = value;
    return (setsockopt(fd, SOL_SOCKET, SO_LINGER, &data, sizeof(data)) == 0);
}

} // namespace vespalib