I am trying开发者_JS百科 to convert strings into Inetaddress
. I am not trying to resolve hostnames: the strings are ipv4 addresses. Does InetAddress.getByName(String host)
work? Or do I have to manually parse it?
com.google.common.net.InetAddresses.forString(String ipString)
is better for this as it will not do a DNS lookup regardless of what string is passed to it.
Yes, that will work. The API is very clear on this ("The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address."), and of course you could easily check yourself.
Beware: it seems that parsing an invalid address such as InetAddress.getByName("999.999.999.999"
) will not result in an exception as one might expect from the documentation's phrase:
the validity of the address format is checked
Empirically, I find myself getting an InetAddress instance with the local machine's raw IP address and the invalid IP address as the host name. Certainly this was not what I expected!
You could try using a regular expression to filter-out non-numeric IP addresses before passing the String
to getByName()
. Then getByName()
will not try name resolution.
The open-source IPAddress Java library will validate all standard representations of IPv6 and IPv4 and will do so without DNS lookup. Disclaimer: I am the project manager of that library.
The following code will do what you are requesting:
String s = "1.2.3.4";
try {
IPAddressString str = new IPAddressString(s);
IPAddress addr = str.toAddress();
InetAddress inetAddress = addr.toInetAddress(); //IPv4 or IPv6
if(addr.isIPv4() || addr.isIPv4Convertible()) {//IPv4 specific
IPv4Address ipv4Addr = addr.toIPv4();
Inet4Address inetAddr = ipv4Addr.toInetAddress();
//use address
}
} catch(AddressStringException e) {
//e.getMessage has validation error
}
精彩评论