* @brief Opens the socket and binds it to the specified address and port. * @param port The port to bind to. * @param address The address to bind to. If "0.0.0.0" for IPv4 (or "::" for IPv6), * we bind to all interfaces, meaning we can receive packets from any network * interface. Binding to "127.0.0.1" (or "::1" for IPv6) will only allow * packets from the lo
| 6709 | * packets from the loopback interface, which can be handy for testing. |
| 6710 | */ |
| 6711 | addressed_socket_t rpc_server_socket(std::uint16_t port, std::string const &address = "0.0.0.0") { |
| 6712 | addressed_socket_t server; |
| 6713 | // Initialize socket |
| 6714 | server.socket_descriptor = socket(AF_INET, SOCK_DGRAM, 0); |
| 6715 | if (server.socket_descriptor < 0) raise_system_error("Failed to create socket"); |
| 6716 | |
| 6717 | // Allow port reuse |
| 6718 | int const socket_option = 1; |
| 6719 | if (setsockopt(server.socket_descriptor, SOL_SOCKET, SO_REUSEADDR, &socket_option, sizeof(socket_option)) < 0) |
| 6720 | raise_system_error("Failed to set SO_REUSEADDR"); |
| 6721 | |
| 6722 | // Bind to address and port |
| 6723 | server.server_address.sin_family = AF_INET; |
| 6724 | server.server_address.sin_addr.s_addr = inet_addr(address.c_str()); |
| 6725 | server.server_address.sin_port = htons(port); |
| 6726 | if (bind(server.socket_descriptor, reinterpret_cast<sockaddr *>(&server.server_address), |
| 6727 | sizeof(server.server_address)) < 0) |
| 6728 | raise_system_error("Failed to bind socket"); |
| 6729 | return server; |
| 6730 | } |
| 6731 | |
| 6732 | /** |
| 6733 | * @brief Opens the socket and resolves the server address. |
no test coverage detected