Open
Description
openedon Sep 11, 2023
InetAddress.toString() outputs a string in the format <hostname>/<address>
. I have use cases where I need to convert this string back to an Inet4Address or Inet6Address, which I think would be useful to include in Guava's InetAddresses class.
The code I'm using currently looks like this:
public static InetAddress forHostnameAddressString(String hostAndAddr) throws UnknownHostException {
checkNotNull(hostAndAddr);
if (hostAndAddr.contains("/")) {
String[] parts = hostAndAddr.split("/", 2);
String host = parts[0];
String addr = parts[1];
InetAddress inetAddress = InetAddresses.forString(addr);
if (inetAddress instanceof Inet4Address) {
return Inet4Address.getByAddress(host, inetAddress.getAddress());
} else if (inetAddress instanceof Inet6Address) {
return Inet6Address.getByAddress(host, inetAddress.getAddress(), ((Inet6Address) inetAddress).getScopeId());
} else {
throw new IllegalStateException("InetAddress must be an instance of Inet4Address or Inet6Address");
}
} else {
return InetAddresses.forString(hostAndAddr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment