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(); } }
Programming Tips - Java: Pretty IP-address for display
Date: 2019may6
Language: Java
Q. Java: Pretty IP-address for display
A. Here's a function that does that