udp_client.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 <spdlog/common.h>
  10. #include <spdlog/details/os.h>
  11. #include <cstring>
  12. #include <sys/socket.h>
  13. #include <netinet/in.h>
  14. #include <arpa/inet.h>
  15. #include <unistd.h>
  16. #include <netdb.h>
  17. #include <netinet/udp.h>
  18. #include <string>
  19. namespace spdlog {
  20. namespace details {
  21. class udp_client
  22. {
  23. static constexpr int TX_BUFFER_SIZE = 1024 * 10;
  24. int socket_ = -1;
  25. struct sockaddr_in sockAddr_;
  26. void cleanup_()
  27. {
  28. if (socket_ != -1)
  29. {
  30. ::close(socket_);
  31. socket_ = -1;
  32. }
  33. }
  34. public:
  35. udp_client(const std::string &host, uint16_t port)
  36. {
  37. socket_ = ::socket(PF_INET, SOCK_DGRAM, 0);
  38. if (socket_ < 0)
  39. {
  40. throw_spdlog_ex("error: Create Socket Failed!");
  41. }
  42. int option_value = TX_BUFFER_SIZE;
  43. if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0)
  44. {
  45. cleanup_();
  46. throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!");
  47. }
  48. sockAddr_.sin_family = AF_INET;
  49. sockAddr_.sin_port = htons(port);
  50. if (::inet_aton(host.c_str(), &sockAddr_.sin_addr) == 0)
  51. {
  52. cleanup_();
  53. throw_spdlog_ex("error: Invalid address!");
  54. }
  55. ::memset(sockAddr_.sin_zero, 0x00, sizeof(sockAddr_.sin_zero));
  56. }
  57. ~udp_client()
  58. {
  59. cleanup_();
  60. }
  61. int fd() const
  62. {
  63. return socket_;
  64. }
  65. // Send exactly n_bytes of the given data.
  66. // On error close the connection and throw.
  67. void send(const char *data, size_t n_bytes)
  68. {
  69. ssize_t toslen = 0;
  70. socklen_t tolen = sizeof(struct sockaddr);
  71. if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) == -1)
  72. {
  73. throw_spdlog_ex("sendto(2) failed", errno);
  74. }
  75. }
  76. };
  77. } // namespace details
  78. } // namespace spdlog