javainetaddress

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 www.google.com?

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.


Solution

  • 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:

    check("1.2.3.4");
    check("1.2.a.4");
    check("::1");
    check("[::1]");
    check("1.2.?.4");  
    
    static void check(String hostStr) {
       HostName host = new HostName(hostStr);
       try {
           host.validate();
           if(host.isAddress()) {
               IPAddress addr = host.asAddress();
               System.out.println(addr.getIPVersion() + " address: " + addr);
           } else {
               System.out.println("host name: " + host);
           }
       } catch(HostNameException e) {
           System.out.println(e.getMessage());
       }
    }
    

    Output:

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