OpenVPN 3 Core Library
Loading...
Searching...
No Matches
sockopt.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#ifndef OPENVPN_COMMON_SOCKOPT_H
13#define OPENVPN_COMMON_SOCKOPT_H
14
16
17#if !defined(OPENVPN_PLATFORM_WIN)
18
19#include <unistd.h>
20#include <fcntl.h>
21#include <sys/types.h>
22#include <sys/socket.h>
23#include <netinet/in.h>
24#include <netinet/tcp.h>
25
27
28namespace openvpn::SockOpt {
29
30#ifdef SO_REUSEPORT
31// set SO_REUSEPORT for inter-thread load balancing
32inline void reuseport(const int fd)
33{
34 int on = 1;
35 if (::setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)) < 0)
36 throw Exception("error setting SO_REUSEPORT on socket");
37}
38#endif
39
40// set SO_REUSEADDR for TCP
41inline void reuseaddr(const int fd)
42{
43 int on = 1;
44 if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) < 0)
45 throw Exception("error setting SO_REUSEADDR on socket");
46}
47
48// set TCP_NODELAY for TCP
49inline void tcp_nodelay(const int fd)
50{
51 int state = 1;
52 if (::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&state, sizeof(state)) != 0)
53 throw Exception("error setting TCP_NODELAY on socket");
54}
55
56// set FD_CLOEXEC to prevent fd from being passed across execs
57inline void set_cloexec(const int fd)
58{
59 if (::fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
60 throw Exception("error setting FD_CLOEXEC on file-descriptor/socket");
61}
62
63// set non-block mode on socket
64static inline void set_nonblock(const int fd)
65{
66 if (::fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
67 throw Exception("error setting socket to non-blocking mode");
68}
69} // namespace openvpn::SockOpt
70
71#endif
72#endif
static void set_nonblock(const int fd)
Definition sockopt.hpp:64
void set_cloexec(const int fd)
Definition sockopt.hpp:57
void tcp_nodelay(const int fd)
Definition sockopt.hpp:49
void reuseaddr(const int fd)
Definition sockopt.hpp:41