xref: /aosp_15_r20/external/grpc-grpc/test/core/util/resolve_localhost_ip46.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 
19 #include "test/core/util/resolve_localhost_ip46.h"
20 
21 #include <memory>
22 #include <vector>
23 
24 #include "absl/status/statusor.h"
25 #include "absl/strings/str_cat.h"
26 
27 #include <grpc/support/log.h>
28 #include <grpc/support/sync.h>
29 
30 #include "src/core/lib/iomgr/resolve_address.h"
31 #include "src/core/lib/iomgr/resolved_address.h"
32 #include "src/core/lib/iomgr/sockaddr.h"
33 
34 namespace grpc_core {
35 namespace {
36 
37 bool localhost_to_ipv4 = false;
38 bool localhost_to_ipv6 = false;
39 gpr_once g_resolve_localhost_ipv46 = GPR_ONCE_INIT;
40 
InitResolveLocalhost()41 void InitResolveLocalhost() {
42   absl::StatusOr<std::vector<grpc_resolved_address>> addresses_or =
43       GetDNSResolver()->LookupHostnameBlocking("localhost", "https");
44   GPR_ASSERT(addresses_or.ok());
45   for (const auto& addr : *addresses_or) {
46     const grpc_sockaddr* sock_addr =
47         reinterpret_cast<const grpc_sockaddr*>(&addr);
48     if (sock_addr->sa_family == GRPC_AF_INET) {
49       localhost_to_ipv4 = true;
50     } else if (sock_addr->sa_family == GRPC_AF_INET6) {
51       localhost_to_ipv6 = true;
52     }
53   }
54 }
55 }  // namespace
56 
LocalhostResolves(bool * ipv4,bool * ipv6)57 void LocalhostResolves(bool* ipv4, bool* ipv6) {
58   gpr_once_init(&g_resolve_localhost_ipv46, InitResolveLocalhost);
59   *ipv4 = localhost_to_ipv4;
60   *ipv6 = localhost_to_ipv6;
61 }
62 
RunningWithIPv6Only()63 bool RunningWithIPv6Only() {
64   bool localhost_resolves_to_ipv4 = false;
65   bool localhost_resolves_to_ipv6 = false;
66   LocalhostResolves(&localhost_resolves_to_ipv4, &localhost_resolves_to_ipv6);
67   return !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
68 }
69 
LocalIp()70 absl::string_view LocalIp() {
71   return RunningWithIPv6Only() ? "[::1]" : "127.0.0.1";
72 }
73 
LocalIpAndPort(int port)74 std::string LocalIpAndPort(int port) {
75   return absl::StrCat(LocalIp(), ":", port);
76 }
77 
LocalIpUri(int port)78 std::string LocalIpUri(int port) {
79   return absl::StrCat(
80       RunningWithIPv6Only() ? "ipv6:%5b::1%5d:" : "ipv4:127.0.0.1:", port);
81 }
82 
83 }  // namespace grpc_core
84