Programming Tips - Java: An easy way to do a DNS lookup

Date: 2016mar22 Update: 2025sep22 Language: Java Q. Java: An easy way to do a DNS lookup A. Use the InetAddress class. Shown in this full example:
import java.io.IOException; import java.net.InetAddress; import java.net.Inet4Address; import java.net.UnknownHostException; import java.util.ArrayList; class Demo { enum LookupOption { ALL, IPV4_ONLY }; static ArrayList<String> lookup(final String strSiteName, final LookupOption opt) { ArrayList<String> out = new ArrayList<>(); try { InetAddress[] addresses = InetAddress.getAllByName(strSiteName); for (var address: addresses) { boolean wanted = true; if (opt == LookupOption.IPV4_ONLY) { wanted = address instanceof Inet4Address; } if (wanted) { out.add(address.getHostAddress()); } } } catch (UnknownHostException ex) { // You can remove this print System.err.println("Could not lookup '" + strSiteName + "' because " + ex.getMessage()); return out; } return out; } public static final void main(String[] arg) { { ArrayList<String> strAddresses = lookup("google.com", LookupOption.IPV4_ONLY); System.out.println("google=" + strAddresses); } { ArrayList<String> strAddresses = lookup("junk.bogus", LookupOption.ALL); System.out.println("junk=" + strAddresses); } } }
Output:
google=[172.217.4.206] Could not lookup 'junk.bogus' because junk.bogus: Name or service not known junk=[]