1 | // Copyright(c) 2015-present, Gabi Melman & spdlog contributors. |
2 | // Distributed under the MIT License (http://opensource.org/licenses/MIT) |
3 | |
4 | #pragma once |
5 | |
6 | // Helper RAII over unix udp client socket. |
7 | // Will throw on construction if the socket creation failed. |
8 | |
9 | #ifdef _WIN32 |
10 | # error "include udp_client-windows.h instead" |
11 | #endif |
12 | |
13 | #include <spdlog/common.h> |
14 | #include <spdlog/details/os.h> |
15 | |
16 | #include <sys/socket.h> |
17 | #include <netinet/in.h> |
18 | #include <arpa/inet.h> |
19 | #include <unistd.h> |
20 | #include <netdb.h> |
21 | #include <netinet/udp.h> |
22 | |
23 | #include <string> |
24 | |
25 | namespace spdlog { |
26 | namespace details { |
27 | |
28 | class udp_client |
29 | { |
30 | static constexpr int TX_BUFFER_SIZE = 1024 * 10; |
31 | int socket_ = -1; |
32 | struct sockaddr_in sockAddr_; |
33 | |
34 | void cleanup_() |
35 | { |
36 | if (socket_ != -1) |
37 | { |
38 | ::close(socket_); |
39 | socket_ = -1; |
40 | } |
41 | } |
42 | |
43 | public: |
44 | udp_client(const std::string &host, uint16_t port) |
45 | { |
46 | socket_ = ::socket(PF_INET, SOCK_DGRAM, 0); |
47 | if (socket_ < 0) |
48 | { |
49 | throw_spdlog_ex("error: Create Socket Failed!" ); |
50 | } |
51 | |
52 | int option_value = TX_BUFFER_SIZE; |
53 | if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0) |
54 | { |
55 | cleanup_(); |
56 | throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!" ); |
57 | } |
58 | |
59 | sockAddr_.sin_family = AF_INET; |
60 | sockAddr_.sin_port = htons(port); |
61 | |
62 | if (::inet_aton(host.c_str(), &sockAddr_.sin_addr) == 0) |
63 | { |
64 | cleanup_(); |
65 | throw_spdlog_ex("error: Invalid address!" ); |
66 | } |
67 | |
68 | ::memset(sockAddr_.sin_zero, 0x00, sizeof(sockAddr_.sin_zero)); |
69 | } |
70 | |
71 | ~udp_client() |
72 | { |
73 | cleanup_(); |
74 | } |
75 | |
76 | int fd() const |
77 | { |
78 | return socket_; |
79 | } |
80 | |
81 | // Send exactly n_bytes of the given data. |
82 | // On error close the connection and throw. |
83 | void send(const char *data, size_t n_bytes) |
84 | { |
85 | ssize_t toslen = 0; |
86 | socklen_t tolen = sizeof(struct sockaddr); |
87 | if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) == -1) |
88 | { |
89 | throw_spdlog_ex("sendto(2) failed" , errno); |
90 | } |
91 | } |
92 | }; |
93 | } // namespace details |
94 | } // namespace spdlog |
95 | |