Java regex for accepting a valid hostname,IPv4, or IPv6 address

こ雲淡風輕ζ 提交于 2019-12-22 05:15:16

问题


Anyone have a good (preferably tested) regex for accpeting only a valid DNS hostname, IPv4 or IPv6 address?


回答1:


I understand that you may be forced to use a regex. However, if possible it is better to avoid using regexes for this task and use a Java library class to do the validation instead.

If you want to do validation and DNS lookup together, then InetAddress.getByName(String) is a good choice. This will cope with DNS, IPv4 and IPv6 in one go, and it returns 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 a syntactic validation, then Apache commons has a couple of classes that should do the job: DomainValidator and InetAddressValidator.




回答2:


Guava has a new class HostSpecifier. It will even validate that the host name (if it is a host name) ends in a valid "public suffix" (e.g., ".com", ".co.uk", etc.), based on the latest mozilla public suffix list. That's something you would NOT want to attempt with a hand-crafted regex!




回答3:


Inspired by the code I found in this post, I created the following validator method that seems to suit simple validation needs quite nicely. By reading the JavaDoc of URI I removed some false positives such as "host:80" and "hostname/page", but I cannot guarantee there are some false positives left.

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;
    }
}


来源:https://stackoverflow.com/questions/3114595/java-regex-for-accepting-a-valid-hostname-ipv4-or-ipv6-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!