rpc_basic.cc 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright (c) 2022 Sogou, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #ifdef _WIN32
  14. #include <workflow/PlatformSocket.h>
  15. #else
  16. #include <sys/types.h>
  17. #include <sys/socket.h>
  18. #endif
  19. #include "rpc_basic.h"
  20. #include "rpc_module.h"
  21. namespace srpc
  22. {
  23. void RPCCommon::log_format(std::string& key, std::string& value,
  24. const RPCLogVector& fields)
  25. {
  26. if (fields.size() == 0)
  27. return;
  28. char buffer[100];
  29. snprintf(buffer, 100, "%s%c%lld", SRPC_SPAN_LOG, ' ', GET_CURRENT_MS());
  30. key = std::move(buffer);
  31. value = "{\"";
  32. for (auto& field : fields)
  33. {
  34. value = value + std::move(field.first) + "\":\""
  35. + std::move(field.second) + "\",";
  36. }
  37. value[value.length() - 1] = '}';
  38. }
  39. bool RPCCommon::addr_to_string(const struct sockaddr *addr,
  40. char *ip_str, socklen_t len,
  41. unsigned short *port)
  42. {
  43. const char *ret = NULL;
  44. if (addr->sa_family == AF_INET)
  45. {
  46. struct sockaddr_in *sin = (struct sockaddr_in *)addr;
  47. ret = inet_ntop(AF_INET, &sin->sin_addr, ip_str, len);
  48. *port = ntohs(sin->sin_port);
  49. }
  50. else if (addr->sa_family == AF_INET6)
  51. {
  52. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
  53. ret = inet_ntop(AF_INET6, &sin6->sin6_addr, ip_str, len);
  54. *port = ntohs(sin6->sin6_port);
  55. }
  56. else
  57. errno = EINVAL;
  58. return ret != NULL;
  59. }
  60. } // namespace srpc