I have a local IP address in dotted decimal notation in a String
. I want to convert it to an InetAddress
to feed it to Socket
, but I need to do it without doing a DNS lookup (because this might cause lengthy timeouts).
Is there a ready method for that, or do I need to split the String
and create the InetAddress
from its bytes?
Update The factory methods InetAddress.getByName()
and InetAddress.getByAddress()
don't seem to be a good fit, as they both also accept hostnames such as java.sun.com
. There is no saying if they will try to contact a DNS server in their implementation.
getByAddress(String host, byte[] addr) Creates an InetAddress based on the provided host name and IP address. static InetAddress. getByName(String host) Determines the IP address of a host, given the host's name.
address is a string or integer representing the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default.
Do like this
InetAddress inetAddress = InetAddress.getByName("192.168.0.105");
If a literal IP address is supplied, only the validity of the address format is checked.
java source code
// if host is an IP address, we won't do further lookup if (Character.digit(host.charAt(0), 16) != -1 || (host.charAt(0) == ':')) { }
You can use Guava's InetAddresses#forString()
which is specifically documented for your use case:
Returns the
InetAddress
having the given string representation.
This deliberately avoids all nameservice lookups (e.g. no DNS).
(emphasis added)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With