Does anyone have a good (preferably tested) regex for accepting only a valid DNS hostname, IPv4, or IPv6 address?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 wrappedInetAddressinstance 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:
DomainValidatorandInetAddressValidator.