The java.net.InetAddress API resolves host names to Internet Protocol (IP) addresses, and vice versa. In the current implementation, this API uses the OS’s native resolver (typically configured with a combination of a local hosts file and the DNS).
The Java 18 API defines a service-provider interface (SPI) for host name and address resolution, so that java.net.InetAddress can make
use of resolvers other than the platform’s built-in resolver.
The new InetAddress API uses a Service Loader to locate a resolver provider.
- InetAddressResolverProvider — an abstract class defining the service to be located by java.util.ServiceLoader.
- InetAddressResolver — an interface that defines methods for the fundamental forward and reverse lookup operations.
- InetAddressResolver.LookupPolicy — a class whose instances describe the characteristics of a resolution request,
- InetAddressResolverProvider.Configuration — an interface describing the platform’s built-in configuration for resolution operations.
Let’s see it with a practical example. We will create a sample AddressResolver Class which extends java.net.spi.InetAddressResolver:
package com.sample.provider;
import java.net.InetAddress;import java.net.UnknownHostException;import java.net.spi.InetAddressResolver;import java.util.stream.Stream;public class MyAddressResolver implements InetAddressResolver {@Overridepublic Stream<InetAddress> lookupByName(String host, LookupPolicy lookupPolicy)throws UnknownHostException {if (host.equals("fedora")) {return Stream.of(InetAddress.getByAddress(new byte[] {192, 168, 10, 1}));}return Stream.of(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}));}@Overridepublic String lookupByAddress(byte[] addr) {throw new UnsupportedOperationException();}}
The Class contains a minimal address resolution policy to return the IP Address 192.168.10.1 for the Host “fedora”.
Next, let’s extend the class InetAddressResolverProvider to return an instance of our AddressResolver Class:
package com.sample.provider;
import java.net.spi.InetAddressResolver;import java.net.spi.InetAddressResolverProvider;public class MyAddressResolverProvider extends InetAddressResolverProvider {@Overridepublic InetAddressResolver get(Configuration configuration) {return new MyAddressResolver();}@Overridepublic String name() {return "MyAddressResolverProvider Internet Address Resolver Provider";}}
Finally, to register the Class as a Service Provider Interface, we need to add to the Service Provider Configuration Class in a file META-INF/services/java.net.spi.InetAddressResolverProvider
com.sample.provider.MyAddressResolverProvider
That’s all. You can test the InetAddress resolution as follows:
public class App {public static void main(String[] args) throws UnknownHostException {InetAddress[] addresses = InetAddress.getAllByName("fedora");System.out.println("addresses = " + Arrays.toString(addresses));}}