1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.resolver.dns;
17
18 import io.netty.util.internal.SocketUtils;
19 import io.netty.util.internal.logging.InternalLogger;
20 import io.netty.util.internal.logging.InternalLoggerFactory;
21
22 import javax.naming.Context;
23 import javax.naming.NamingException;
24 import javax.naming.directory.DirContext;
25 import javax.naming.directory.InitialDirContext;
26 import java.net.InetSocketAddress;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.Hashtable;
30 import java.util.List;
31
32 final class DirContextUtils {
33 private static final InternalLogger logger =
34 InternalLoggerFactory.getInstance(DirContextUtils.class);
35
36 private DirContextUtils() { }
37
38 static void addNameServers(List<InetSocketAddress> defaultNameServers, int defaultPort) {
39
40
41
42
43
44 Hashtable<String, String> env = new Hashtable<String, String>();
45 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
46 env.put("java.naming.provider.url", "dns://");
47
48 try {
49 DirContext ctx = new InitialDirContext(env);
50 String dnsUrls = (String) ctx.getEnvironment().get("java.naming.provider.url");
51
52 if (dnsUrls != null && !dnsUrls.isEmpty()) {
53 String[] servers = dnsUrls.split(" ");
54 for (String server : servers) {
55 try {
56 URI uri = new URI(server);
57 String host = uri.getHost();
58 if (host == null || host.isEmpty()) {
59 logger.debug(
60 "Skipping a nameserver URI as host portion could not be extracted: {}", server);
61
62 continue;
63 }
64 int port = uri.getPort();
65 defaultNameServers.add(SocketUtils.socketAddress(uri.getHost(), port == -1 ?
66 defaultPort : port));
67 } catch (URISyntaxException e) {
68 logger.debug("Skipping a malformed nameserver URI: {}", server, e);
69 }
70 }
71 }
72 } catch (NamingException ignore) {
73
74 }
75 }
76 }