Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 983
ljbade Avatar asked Jun 24 '10 23:06

ljbade


1 Answers

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.

like image 153
Stephen C Avatar answered Oct 02 '22 15:10

Stephen C