xref: /aosp_15_r20/external/grpc-grpc/test/cpp/naming/utils/dns_resolver.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1#!/usr/bin/env python3
2# Copyright 2015 gRPC authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Makes DNS queries for A records to specified servers"""
16
17import argparse
18import threading
19import time
20
21import twisted.internet.reactor as reactor
22import twisted.internet.task as task
23import twisted.names.client as client
24
25
26def main():
27    argp = argparse.ArgumentParser(description="Make DNS queries for A records")
28    argp.add_argument(
29        "-s",
30        "--server_host",
31        default="127.0.0.1",
32        type=str,
33        help="Host for DNS server to listen on for TCP and UDP.",
34    )
35    argp.add_argument(
36        "-p",
37        "--server_port",
38        default=53,
39        type=int,
40        help="Port that the DNS server is listening on.",
41    )
42    argp.add_argument(
43        "-n",
44        "--qname",
45        default=None,
46        type=str,
47        help="Name of the record to query for. ",
48    )
49    argp.add_argument(
50        "-t",
51        "--timeout",
52        default=1,
53        type=int,
54        help="Force process exit after this number of seconds.",
55    )
56    args = argp.parse_args()
57
58    def OnResolverResultAvailable(result):
59        answers, authority, additional = result
60        for a in answers:
61            print(a.payload)
62
63    def BeginQuery(reactor, qname):
64        servers = [(args.server_host, args.server_port)]
65        resolver = client.Resolver(servers=servers)
66        deferred_result = resolver.lookupAddress(args.qname)
67        deferred_result.addCallback(OnResolverResultAvailable)
68        return deferred_result
69
70    task.react(BeginQuery, [args.qname])
71
72
73if __name__ == "__main__":
74    main()
75