I think you've misunderstood how to convert an IP address from String
to byte[]
. The proper way to do that is to parse String
to a sequence of int
s, and then cast each of those to a byte
. But fortunately, InetAddress
already has a method to handle that for you, so you can just write:
private static boolean isPrivateIPAddress(String ipAddress)
{
return InetAddress.getByName(ipAddress).isSiteLocalAddress();
}
(together with whatever validity-checking and error-handling you want).
Note that the above will also handle hostnames, by using DNS lookup. If you don't want that, you'll need to pre-check the IP-address, using something like this:
if(! Pattern.matches("(\d{1,3}\.){3}\d{1,3}", ipAddress)
throw new IllegalArgumentException();
if you're O.K. with only supporting IPv4.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…