Debian Codegraph @

test/core/util/resolve_localhost_ip46.cc

raw
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
26 #include <grpc/support/log.h>
27 #include <grpc/support/sync.h>
28
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
40 void InitResolveLocalhost() {
41 absl::StatusOr<std::vector<grpc_resolved_address>> addresses_or =
42 GetDNSResolver()->LookupHostnameBlocking("localhost", "https");
43 GPR_ASSERT(addresses_or.ok());
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
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
62 } // namespace grpc_core