Java regex to accept the correct hostname, IPv4 or IPv6 address

Does anyone have a good (preferably verified) regular expression for axing only the valid DNS, IPv4, or IPv6 hostname?

+6
java regex ipv4 ipv6 hostname
source share
3 answers

I understand that you can use regex. However, if possible, it is best to avoid using regular expressions for this task and instead use the Java library class for validation.

If you want to check and look up DNS together, then InetAddress.getByName(String) is a good choice. This will work with DNS, IPv4 and IPv6 at a time, and it will return to you a neatly wrapped InetAddress instance that contains both the DNS name (if provided) and the IPv4 or IPv6 address.

If you just want to do the parsing, then the Apache community has several classes that should do the job: DomainValidator and InetAddressValidator .

+18
source share

Guava has a new HostSpecifier class. It will even confirm that the host name (if it is the host name) ends with a valid "public suffix" (for example, ".com", ".co.uk", etc.), Based on the latest public suffix mozilla list. This is something you would not want to try using a regexp with manual control!

+5
source share

Inspired by the code I found in this post , I created the following validator method, which seems to be fairly easy to validate. By reading the JavaDoc URI, I removed some false positives, such as "host: 80" and "hostname / page", but I cannot guarantee that some false positives will remain.

 public static boolean isValidHostNameSyntax(String candidateHost) { if (candidateHost.contains("/")) { return false; } try { // WORKAROUND: add any scheme and port to make the resulting URI valid return new URI("my:// userinfo@ " + candidateHost + ":80").getHost() != null; } catch (URISyntaxException e) { return false; } } 
0
source share

All Articles