Java DNS查询内部实现(4)

package java.net; import java.io.IOException; /* * Package private interface to "implementation" used by * {@link InetAddress}. * <p> * See {@link java.net.Inet4AddressImp} and * {@link java.net.Inet6AddressImp}. * * @since 1.4 */ interface InetAddressImpl { String getLocalHostName() throws UnknownHostException; InetAddress[] lookupAllHostAddr(String hostname) throws UnknownHostException; String getHostByAddr(byte[] addr) throws UnknownHostException; InetAddress anyLocalAddress(); InetAddress loopbackAddress(); boolean isReachable(InetAddress addr, int timeout, NetworkInterface netif, int ttl) throws IOException; }

有两个实现:

Inet4AddressImpl

Inet6AddressImpl

这里我们仅仅挑选Inet4AddressImpl说明。

package java.net; import java.io.IOException; /* * Package private implementation of InetAddressImpl for IPv4. * * @since 1.4 */ class Inet4AddressImpl implements InetAddressImpl { public native String getLocalHostName() throws UnknownHostException; public native InetAddress[] lookupAllHostAddr(String hostname) throws UnknownHostException; public native String getHostByAddr(byte[] addr) throws UnknownHostException; private native boolean isReachable0(byte[] addr, int timeout, byte[] ifaddr, int ttl) throws IOException; public synchronized InetAddress anyLocalAddress() { if (anyLocalAddress == null) { anyLocalAddress = new Inet4Address(); // {0x00,0x00,0x00,0x00} anyLocalAddress.holder().hostName = "0.0.0.0"; } return anyLocalAddress; } public synchronized InetAddress loopbackAddress() { if (loopbackAddress == null) { byte[] loopback = {0x7f,0x00,0x00,0x01}; loopbackAddress = new Inet4Address("localhost", loopback); } return loopbackAddress; } public boolean isReachable(InetAddress addr, int timeout, NetworkInterface netif, int ttl) throws IOException { byte[] ifaddr = null; if (netif != null) { /* * Let's make sure we use an address of the proper family */ java.util.Enumeration<InetAddress> it = netif.getInetAddresses(); InetAddress inetaddr = null; while (!(inetaddr instanceof Inet4Address) && it.hasMoreElements()) inetaddr = it.nextElement(); if (inetaddr instanceof Inet4Address) ifaddr = inetaddr.getAddress(); } return isReachable0(addr.getAddress(), timeout, ifaddr, ttl); } private InetAddress anyLocalAddress; private InetAddress loopbackAddress; }

可以看到这个类基本没有实现什么逻辑,主要实现都是通过JNI调用native方法了。native方法其实就是系统调用了。这里就不展开了,逻辑不外乎就是查看/etc/resolv.conf下配置的nameserver和/etc/hosts下面的配置,然后使用DNS协议查询。

其他NameService通过NameServiceDescriptor来创建相应。NameServiceDescriptor本身也是一个接口:

package sun.net.spi.nameservice; public interface NameServiceDescriptor { /** * Create a new instance of the corresponding name service. */ public NameService createNameService () throws Exception ; /** * Returns this service provider's name * */ public String getProviderName(); /** * Returns this name service type * "dns" "nis" etc */ public String getType(); }

这里我们先看看JDK自带一个实现——DNSNameService。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/2502f6543a00bb6143a79c23ee2f39fb.html