udp_client.h 2.2 KB

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