Programming Tips - Java: Pretty IP-address for display

Date: 2019may6 Update: 2025oct5 Language: Java Q. Java: Pretty IP-address for display A. Here's a function that does that. As shown in a full example:
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; import java.util.Arrays; class Demo { private final static int BYTES_IN_IPV4 = 4; public static String prettyAddress(final InetAddress addr) { if (addr instanceof Inet4Address) { final Inet4Address addr4 = (Inet4Address) addr; return addr4.getHostAddress(); } else if (addr instanceof Inet6Address) { final Inet6Address addr6 = (Inet6Address) addr; if (addr6.isLoopbackAddress()) { return "127.0.0.1"; } else if (addr6.isIPv4CompatibleAddress()) { final byte[] baddr6 = addr6.getAddress(); final byte[] baddr4 = Arrays.copyOfRange(baddr6, baddr6.length - BYTES_IN_IPV4 - 1, baddr6.length - 1); return String.format("%d.%d.%d.%d", baddr4[0], baddr4[1], baddr4[2], baddr4[3]); } else { return addr6.getHostAddress(); } } else { return addr.getHostAddress(); } } public static final void main(String []args) throws UnknownHostException { String host = "google.com"; InetAddress addr = InetAddress.getByName(host); String pretty = prettyAddress(addr); System.out.println("pretty=" + pretty); } }
Output:
pretty=172.217.165.14