IpLiteral { @Nullable public static String ipOrNull(@Nullable String ip) { if (ip == null || ip.isEmpty()) return null; if ("::1".equals(ip) || "127.0.0.1".equals(ip)) return ip; IpFamily format = detectFamily(ip); if (format == IpFamily.IPv4Embedded) { ip = ip.substring(ip.lastIndexOf(':') + 1); } else if (format == IpFamily.Unknown) { ip = null; } return ip; }  @Nullable static String ipOrNull(@Nullable String ip); static IpFamily detectFamily(String ipString);  }
@Test public void ipOrNull_invalid() { assertThat(IpLiteral.ipOrNull("ahola")).isNull(); assertThat(IpLiteral.ipOrNull("/43.0.292.2")).isNull(); assertThat(IpLiteral.ipOrNull("43.0.292.2")).isNull(); assertThat(IpLiteral.ipOrNull("::0000:43.0.192.302")).isNull(); assertThat(IpLiteral.ipOrNull("200000:43.0.192.202")).isNull(); assertThat(IpLiteral.ipOrNull("2001:db8::,c001")).isNull(); assertThat(IpLiteral.ipOrNull("2001db8c001")).isNull(); }
@Test public void ipOrNull_ipv4() { assertThat(IpLiteral.ipOrNull("43.0.192.2")).isEqualTo("43.0.192.2"); }
@Test public void ipOrNull_ipv6() { assertThat(IpLiteral.ipOrNull("2001:db8::c001")).isEqualTo("2001:db8::c001"); }
@Test public void ipOrNull_ipv6_mappedIpv4() { assertThat(IpLiteral.ipOrNull("::FFFF:43.0.192.2")).isEqualTo("43.0.192.2"); }
@Test public void ipOrNull_ipv6_compatIpv4() { assertThat(IpLiteral.ipOrNull("::0000:43.0.192.2")).isEqualTo("43.0.192.2"); }
@Test public void ipOrNullv6_notMappedIpv4() { assertThat(IpLiteral.ipOrNull("::ffef:43.0.192.2")).isNull(); }
@Test public void ipOrNull_ipv6UpperCase() { assertThat(IpLiteral.ipOrNull("2001:DB8::C001")).isEqualTo("2001:DB8::C001"); }
@Test public void ipOrNull_ipv6_compatIpv4_compressed() { assertThat(IpLiteral.ipOrNull("::43.0.192.2")).isEqualTo("43.0.192.2"); }
@Test public void ipOrNullv6_localhost() { assertThat(IpLiteral.ipOrNull("::1")).isEqualTo("::1"); }
@Test public void ipOrNullv4_localhost() { assertThat(IpLiteral.ipOrNull("127.0.0.1")).isEqualTo("127.0.0.1"); }
@Test public void ipOrNullv6_notLocalhost() { assertThat(IpLiteral.ipOrNull("::2")).isEqualTo("::2"); }