OpenCBDC Transaction Processor
Loading...
Searching...
No Matches
tcp_listener.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 "tcp_listener.hpp"
7
8#include <unistd.h>
9
10namespace cbdc::network {
11 auto tcp_listener::listen(const ip_address& local_address,
12 port_number_t local_port) -> bool {
13 auto res0 = get_addrinfo(local_address, local_port);
14 if(!res0) {
15 return false;
16 }
17
18 for(auto* res = res0.get(); res != nullptr; res = res->ai_next) {
19 if(!create_socket(res->ai_family,
20 res->ai_socktype,
21 res->ai_protocol)) {
22 continue;
23 }
24
25 if(!set_sockopts()) {
26 continue;
27 }
28
29 if(bind(m_sock_fd, res->ai_addr, res->ai_addrlen) != 0) {
30 ::close(m_sock_fd);
31 m_sock_fd = -1;
32 continue;
33 }
34
35 static constexpr auto max_listen_queue = 5;
36 if(::listen(m_sock_fd, max_listen_queue) != 0) {
37 ::close(m_sock_fd);
38 m_sock_fd = -1;
39 continue;
40 }
41
42 break;
43 }
44
45 return m_sock_fd != -1;
46 }
47
48 auto tcp_listener::accept(tcp_socket& sock) -> bool {
49 sockaddr cli_addr{};
50 unsigned int cli_len = sizeof(cli_addr);
51 sock.m_sock_fd = ::accept(m_sock_fd, &cli_addr, &cli_len);
52 return sock.m_sock_fd != -1;
53 }
54
56 if(m_sock_fd != -1) {
57 shutdown(m_sock_fd, SHUT_RDWR);
58 ::close(m_sock_fd);
59 m_sock_fd = -1;
60 }
61 }
62
66}
auto listen(const ip_address &local_address, port_number_t local_port) -> bool
Starts the listener on the given local port and address.
void close()
Stops the listener and unblocks any blocking calls associated with this listener.
auto accept(tcp_socket &sock) -> bool
Blocks until an incoming connection is ready and populates the given socket.
Wrapper for a TCP socket.
std::string ip_address
An IP addresses.
Definition socket.hpp:15
unsigned short port_number_t
Port number.
Definition socket.hpp:17