开发者

java string detection of ip

开发者 https://www.devze.com 2023-02-14 07:47 出处:网络
Assume a java string that contai开发者_如何学运维ns an IP (v4 or v6) or a hostname. What is the best way to detect among these cases?

Assume a java string that contai开发者_如何学运维ns 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


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.


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.


Use regular expression to match vs ip, if its not ip then its a hostname.

0

精彩评论

暂无评论...
验证码 换一张
取 消