resolve_localhost_ip46.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. //
  3. // Copyright 2020 gRPC authors.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. //
  18. #include "test/core/util/resolve_localhost_ip46.h"
  19. #include <grpc/support/log.h>
  20. #include "src/core/lib/iomgr/port.h"
  21. #include "src/core/lib/iomgr/resolve_address.h"
  22. #include "src/core/lib/iomgr/sockaddr.h"
  23. namespace grpc_core {
  24. namespace {
  25. bool localhost_to_ipv4 = false;
  26. bool localhost_to_ipv6 = false;
  27. gpr_once g_resolve_localhost_ipv46 = GPR_ONCE_INIT;
  28. void InitResolveLocalhost() {
  29. absl::StatusOr<std::vector<grpc_resolved_address>> addresses_or =
  30. GetDNSResolver()->ResolveNameBlocking("localhost", "https");
  31. GPR_ASSERT(addresses_or.ok());
  32. for (const auto& addr : *addresses_or) {
  33. const grpc_sockaddr* sock_addr =
  34. reinterpret_cast<const grpc_sockaddr*>(&addr);
  35. if (sock_addr->sa_family == GRPC_AF_INET) {
  36. localhost_to_ipv4 = true;
  37. } else if (sock_addr->sa_family == GRPC_AF_INET6) {
  38. localhost_to_ipv6 = true;
  39. }
  40. }
  41. }
  42. } // namespace
  43. void LocalhostResolves(bool* ipv4, bool* ipv6) {
  44. gpr_once_init(&g_resolve_localhost_ipv46, InitResolveLocalhost);
  45. *ipv4 = localhost_to_ipv4;
  46. *ipv6 = localhost_to_ipv6;
  47. }
  48. } // namespace grpc_core