简体   繁体   中英

Convert a String to InetAddress without DNS lookup

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.

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 (eg no DNS).

(emphasis added)

You can do this by using the getByName method. for example:

InetAddress localhost = InetAddress.getByName("127.0.0.1")

As it is described on the java docs:

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

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 str = "fe80:0:0:0:f06c:31b8:cd17:5a44";
        try {
            IPAddressString str = new IPAddressString(str);
            IPAddress addr = str.toAddress();//throws if invalid, without a DNS lookup
            InetAddress inetAddr = addr.toInetAddress();//convert valid address
            //use address
        } catch(AddressStringException e) {
            //e.getMessage has validation error
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM