InetAddress Literal Address Checks

Parse literal IP addresses without DNS and classify them with isLoopback, isSiteLocal, and isAnyLocal probes for validation code.

JavaConfig Management

Code

snippet
import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressChecks {

    public static void main(String[] args) throws UnknownHostException {
        // literal IPs parse without a DNS lookup; only hostnames need resolving
        InetAddress loopback = InetAddress.getByName("127.0.0.1");
        System.out.println(loopback + " loopback=" + loopback.isLoopbackAddress());

        InetAddress v6 = InetAddress.getByName("::1");
        System.out.println(v6 + " loopback=" + v6.isLoopbackAddress());

        InetAddress site = InetAddress.getByName("192.168.1.10");
        System.out.println(site + " siteLocal=" + site.isSiteLocalAddress());

        InetAddress any = InetAddress.getByName("0.0.0.0");
        System.out.println(any + " anyLocal=" + any.isAnyLocalAddress());

        // getLoopbackAddress returns a reusable constant, no parsing per call
        System.out.println("shared loopback: " + InetAddress.getLoopbackAddress().getHostAddress());

        // malformed IPv4 literals throw UnknownHostException right away
        try {
            InetAddress.getByName("999.9.9.9");
        } catch (UnknownHostException e) {
            System.out.println("malformed literal rejected: " + e.getMessage());
        }
    }
}

Inside the snippet

One way to read it: the class InetAddressChecks, doing all the work.

Using it

The demo output is labeled (shared loopback:, malformed literal rejected:); each label names the call that printed it.

Key statements

InetAddress loopback = InetAddress.getByName("127.0.0.1");
InetAddress site = InetAddress.getByName("192.168.1.10");
InetAddress any = InetAddress.getByName("0.0.0.0");

Interactive Tools for This Topic

FAQ

What does InetAddress Literal Address Checks print when run?
No setup needed: run the file and look for labeled lines like `shared loopback:`, `malformed literal rejected:` in the output.