udp_client.h 2.2 KB

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