Reputation: 54094
Assume a java string that contains an IP (v4 or v6) or a hostname.
What is the best way to detect among these cases?
I am not interested so much on whether the IP is in valid range (e.g. 999.999.999.999 for IPv4).
I am interested in just a way to detect if a String is a hostname or an IP (v4 or v6).
Initially I though this:
if(theString.indexOf("@")!=-1){
//Not an Ip
}
but I am not sure if I should always expect a format containing @
always.
Thanks
Upvotes: 0
Views: 2361
Reputation: 1923
A simple set of regular expressions with the Pattern class will work for this:
Pattern validIpAddressRegex = Pattern.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
Pattern validHostnameRegex = Pattern.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$");
// matches(String) Will return a boolean value
validIpAddress.matches("111.222.333.444");
I borrowed the regular expressions from this SO answer. Check the Wikipedia article on hostnames for more on what constitutes a valid hostname.
Upvotes: 2
Reputation: 54342
If your address has colons :
then it is IPv6 address. Rest of chars can be hex digits (0-1, A-F, a-f).
If address has only digits and dots then it is IPv4 address.
If address has any letter then it is hostname (hostname can have digits, dots and other chars as well).
This can be simply implemented as:
public static String kindOfIP(final String addr)
{
if (addr.indexOf(":") >= 0)
return "IPv6";
if (addr.matches("^\\d+\\.\\d+\\.\\d+\\.\\d+$"))
return "IPv4";
return "hostname";
}
This code do not check if address is valid.
Upvotes: 1
Reputation: 4280
Use regular expression to match vs ip, if its not ip then its a hostname.
Upvotes: 0