Java: Common way to validate and convert "host:port" to InetSocketAddress?
I myself propose one possible workaround solution.
Convert a string into URI (this would validate it automatically) and then query the URI's host and port components.
Sadly, an URI with a host component MUST have a scheme. This is why this solution is "not perfect".
String string = ... // some string which has to be validated
try {
// WORKAROUND: add any scheme to make the resulting URI valid.
URI uri = new URI("my://" + string); // may throw URISyntaxException
String host = uri.getHost();
int port = uri.getPort();
if (uri.getHost() == null || uri.getPort() == -1) {
throw new URISyntaxException(uri.toString(),
"URI must have host and port parts");
}
// here, additional checks can be performed, such as
// presence of path, query, fragment, ...
// validation succeeded
return new InetSocketAddress (host, port);
} catch (URISyntaxException ex) {
// validation failed
}
This solution needs no custom string parsing, works with IPv4 (1.1.1.1:123
), IPv6 ([::0]:123
) and host names (my.host.com:123
).
Accidentally, this solution is well suited for my scenario. I was going to use URI schemes anyway.
A regex will do this quite neatly:
Pattern p = Pattern.compile("^\\s*(.*?):(\\d+)\\s*$");
Matcher m = p.matcher("127.0.0.1:8080");
if (m.matches()) {
String host = m.group(1);
int port = Integer.parseInt(m.group(2));
}
You can this in many ways such as making the port optional or doing some validation on the host.
It doesn't answer the question exactly, but this answer could still be useful others like me who just want to parse a host and port, but not necessarily a full InetAddress
. Guava has a HostAndPort class with a parseString
method.