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