src/corosio/src/udp_socket.cpp

97.7% Lines (42/0/43) 100.0% List of functions (10/0/10)
udp_socket.cpp
f(x) Functions (10)
Line TLA Hits Source Code
1 //
2 // Copyright (c) 2026 Steve Gerbino
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // Official repository: https://github.com/cppalliance/corosio
8 //
9
10 #include <boost/corosio/udp_socket.hpp>
11 #include <boost/corosio/detail/except.hpp>
12 #include <boost/corosio/detail/platform.hpp>
13
14 #include <boost/corosio/detail/udp_service.hpp>
15
16 namespace boost::corosio {
17
18 235x udp_socket::~udp_socket()
19 {
20 235x close();
21 235x }
22
23 195x udp_socket::udp_socket(capy::execution_context& ctx)
24 195x : io_object(create_handle<detail::udp_service>(ctx))
25 {
26 195x }
27
28 void
29 212x udp_socket::open(udp proto)
30 {
31 212x if (is_open())
32 3x return;
33 209x open_for_family(proto.family(), proto.type(), proto.protocol());
34 }
35
36 void
37 209x udp_socket::open_for_family(int family, int type, int protocol)
38 {
39 209x auto& svc = static_cast<detail::udp_service&>(h_.service());
40 209x std::error_code ec = svc.open_datagram_socket(
41 209x static_cast<udp_socket::implementation&>(*h_.get()), family, type,
42 protocol);
43 209x if (ec)
44 detail::throw_system_error(ec, "udp_socket::open");
45 209x }
46
47 void
48 317x udp_socket::close()
49 {
50 317x if (!is_open())
51 108x return;
52 209x h_.service().close(h_);
53 }
54
55 std::error_code
56 123x udp_socket::bind(endpoint ep)
57 {
58 123x if (!is_open())
59 2x detail::throw_logic_error("bind: socket not open");
60 121x auto& svc = static_cast<detail::udp_service&>(h_.service());
61 121x return svc.bind_datagram(
62 242x static_cast<udp_socket::implementation&>(*h_.get()), ep);
63 }
64
65 void
66 15x udp_socket::cancel()
67 {
68 15x if (!is_open())
69 2x return;
70 13x get().cancel();
71 }
72
73 native_handle_type
74 6x udp_socket::native_handle() const noexcept
75 {
76 6x if (!is_open())
77 {
78 #if BOOST_COROSIO_HAS_IOCP
79 return static_cast<native_handle_type>(~0ull); // INVALID_SOCKET
80 #else
81 2x return -1;
82 #endif
83 }
84 4x return get().native_handle();
85 }
86
87 endpoint
88 72x udp_socket::local_endpoint() const noexcept
89 {
90 72x if (!is_open())
91 2x return endpoint{};
92 70x return get().local_endpoint();
93 }
94
95 endpoint
96 6x udp_socket::remote_endpoint() const noexcept
97 {
98 6x if (!is_open())
99 2x return endpoint{};
100 4x return get().remote_endpoint();
101 }
102
103 } // namespace boost::corosio
104