Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to InetAddress without DNS lookup

Tags:

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.

like image 912
Bart Friederichs Avatar asked Dec 11 '13 12:12

Bart Friederichs


People also ask

What is use of InetAddress getByName () function?

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.

Are IP addresses strings?

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.


2 Answers

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) == ':')) {  } 
like image 195
Prabhakaran Ramaswamy Avatar answered Sep 18 '22 09:09

Prabhakaran Ramaswamy


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)

like image 26
Matt Ball Avatar answered Sep 21 '22 09:09

Matt Ball