Photon 1.0.0
Loading...
Searching...
No Matches
udp_client.h
Go to the documentation of this file.
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
25namespace spdlog
26{
27 namespace details
28 {
29
30 class udp_client
31 {
32 static constexpr int TX_BUFFER_SIZE = 1024 * 10;
33 int socket_ = -1;
34 struct sockaddr_in sockAddr_;
35
36 void cleanup_()
37 {
38 if (socket_ != -1)
39 {
40 ::close(socket_);
41 socket_ = -1;
42 }
43 }
44
45 public:
46 udp_client(const std::string& host, uint16_t port)
47 {
48 socket_ = ::socket(PF_INET, SOCK_DGRAM, 0);
49 if (socket_ < 0)
50 {
51 throw_spdlog_ex("error: Create Socket Failed!");
52 }
53
54 int option_value = TX_BUFFER_SIZE;
55 if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char*>(&option_value), sizeof(option_value)) < 0)
56 {
57 cleanup_();
58 throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!");
59 }
60
61 sockAddr_.sin_family = AF_INET;
62 sockAddr_.sin_port = htons(port);
63
64 if (::inet_aton(host.c_str(), &sockAddr_.sin_addr) == 0)
65 {
66 cleanup_();
67 throw_spdlog_ex("error: Invalid address!");
68 }
69
70 ::memset(sockAddr_.sin_zero, 0x00, sizeof(sockAddr_.sin_zero));
71 }
72
74 {
75 cleanup_();
76 }
77
78 int fd() const
79 {
80 return socket_;
81 }
82
83 // Send exactly n_bytes of the given data.
84 // On error close the connection and throw.
85 void send(const char* data, size_t n_bytes)
86 {
87 ssize_t toslen = 0;
88 socklen_t tolen = sizeof(struct sockaddr);
89 if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr*)&sockAddr_, tolen)) == -1)
90 {
91 throw_spdlog_ex("sendto(2) failed", errno);
92 }
93 }
94 };
95 } // namespace details
96} // namespace spdlog
static constexpr int TX_BUFFER_SIZE
Definition udp_client-windows.h:30
void cleanup_()
Definition udp_client.h:36
SOCKET socket_
Definition udp_client-windows.h:31
~udp_client()
Definition udp_client.h:73
int fd() const
Definition udp_client.h:78
udp_client(const std::string &host, uint16_t port)
Definition udp_client.h:46
void send(const char *data, size_t n_bytes)
Definition udp_client.h:85
struct sockaddr_in sockAddr_
Definition udp_client.h:34
Definition async.h:26
SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno)
Definition common-inl.h:75
Definition format.h:1901
annotation details
Definition tag_strings.h:125