OpenCBDC Transaction Processor
Loading...
Searching...
No Matches
socket.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 MIT Digital Currency Initiative,
2// Federal Reserve Bank of Boston
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include "socket.hpp"
7
8#include <csignal>
9#include <unistd.h>
10
11namespace cbdc::network {
12 socket::socket() {
13 // Ignore SIGPIPE if the socket disconnects and we try to write to it
14 static std::atomic_flag sigpipe_ignored = ATOMIC_FLAG_INIT;
15 if(!sigpipe_ignored.test_and_set()) {
16 // The definition of SIG_IGN contains a c-style cast and it's
17 // implementation-defined in a standard library header so there's
18 // nothing we can do about it.
19 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
20 std::signal(SIGPIPE, SIG_IGN);
21 }
22 }
23
24 auto socket::get_addrinfo(const ip_address& address, port_number_t port)
25 -> std::shared_ptr<addrinfo> {
26 addrinfo hints{};
27 hints.ai_family = PF_UNSPEC;
28 hints.ai_socktype = SOCK_STREAM;
29
30 addrinfo* res0{};
31
32 auto port_str = std::to_string(port);
33 auto error
34 = getaddrinfo(address.c_str(), port_str.c_str(), &hints, &res0);
35 if(error != 0) {
36 return nullptr;
37 }
38
39 auto ret = std::shared_ptr<addrinfo>(res0, [](addrinfo* p) {
40 freeaddrinfo(p);
41 });
42 return ret;
43 }
44
45 auto socket::create_socket(int domain, int type, int protocol) -> bool {
46 m_sock_fd = ::socket(domain, type, protocol);
47 return m_sock_fd != -1;
48 }
49
50 auto socket::set_sockopts() -> bool {
51 static constexpr int one = 1;
52 if(setsockopt(m_sock_fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))
53 != 0) {
54 ::close(m_sock_fd);
55 m_sock_fd = -1;
56 return false;
57 }
58 return true;
59 }
60}
@ error
Serious, critical errors.
std::string ip_address
An IP addresses.
Definition socket.hpp:15
unsigned short port_number_t
Port number.
Definition socket.hpp:17