Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is a hostname or an ip-address in Java

I want to check if a string is a hostname or an ip-address in Java. Is there an API to do it or must I write a parser myself?

The problem is complex because there are IPv4 addresses, short and long IPv6 addresses, short hostnames and FQDN host names.

like image 756
Horcrux7 Avatar asked Mar 31 '12 07:03

Horcrux7


3 Answers

There doesn't appear to be an API, but writing such function doesn't seem to be very difficult. You can check the following conditions in your code:

  1. If sourceStr contains ":" but no "." -> IPv6
  2. If sourceStr.matches("^.[0-9]{1,3}/..[0-9]{1,3}/..[0-9]{1,3}/..[0-9]{1,3}") == true) -> IPv4
  3. If sourceStr contains "." -> FQDN host name
  4. Otherwise it must be a short hostname
like image 116
BluesRockAddict Avatar answered Sep 22 '22 11:09

BluesRockAddict


To expand @MrGomez 's answer, Use InetAddresses to validate IP Addresses and InternetDomainName to validate hostnames (FQDN).

Example:

public static boolean validate(final String hostname) {
        return InetAddresses.isUriInetAddress(hostname) || InternetDomainName.isValid(hostname);
    }
like image 24
GMouaad Avatar answered Sep 20 '22 11:09

GMouaad


While you could theoretically write rules to handle these cases yourself, using the usual cadre of RFCs, I'd instead look at the entirety of this class in Google Guava, especially the corner cases, such as how it resolves the embedding of 4-in-6 addresses.

As for determining if you have a FQDN, see if coercion to IP address fails, then try to resolve it against DNS. Anything else should, given your input cases, be a hostname or local resolution that isn't fully qualified.

like image 44
MrGomez Avatar answered Sep 23 '22 11:09

MrGomez