How can I check if a String is IPv4 / IPv6 or domain name? (Java)

How can I check if a string matches a IPv4, IPv6 adress or a domain name like

I found this for IPv4: Validating IPv4 string in Java And the same kind of system works for IPv6 but how can I check domain names?

EDIT: To clarify: I want to check if a string is a valid server address. Valid just means that the FORMAT is correct. The connection will be testet at a different point in the program.


While it is true there are a lot of corner cases, this is straightforward with The IPAddress Java library. I advise against using regular expressions, there are too many variations. Disclaimer: I am the project manager of the IPAddress library.

Here is sample code:


static void check(String hostStr) {
   HostName host = new HostName(hostStr);
   try {
       if(host.isAddress()) {
           IPAddress addr = host.asAddress();
           System.out.println(addr.getIPVersion() + " address: " + addr);
       } else {
           System.out.println("host name: " + host);
   } catch(HostNameException e) {


IPv4 address:
host name: 1.2.a.4
IPv6 address: ::1
IPv6 address: ::1
1.2.?.4 Host error: invalid character at index 4

Source: stackoverflow