InetAddress Class in Java

Naveen AnamaneniUpdated · 5 min read

The InetAddress class represents an IP address, either IPv4 (such as 192.168.1.20) or IPv6 (such as ::1). It is also Java's way of asking DNS to turn a host name into an address. InetAddress has no public constructor: you get objects from static factory methods. An InetAddress object is immutable. In this lesson, you will learn how to create addresses, look up host names, test what kind of address you have, and combine an address with a port.

Methods

MethodDescription
InetAddress.getByName(host)It is used to get the address of a host name (a DNS lookup) or to parse an address written as text.
InetAddress.getAllByName(host)It returns every address of a host; large sites have several.
InetAddress.getLocalHost()It returns the address of this computer's host name.
InetAddress.getLoopbackAddress()It returns the loopback address, 127.0.0.1, with no lookup.
InetAddress.getByAddress(bytes)It builds an address from 4 bytes (IPv4) or 16 bytes (IPv6).
InetAddress.ofLiteral(text)It parses an address written as text and never does a DNS lookup (Java 22).
getHostAddress()It returns the address as text.
getHostName()It returns the host name, doing a reverse lookup if needed.
getAddress()It returns the raw bytes.
isReachable(timeoutMillis)It tests whether the address answers within the time.
isLoopbackAddress(), isSiteLocalAddress(), isMulticastAddress(), isAnyLocalAddress()They test what kind of address it is.

Inet4Address and Inet6Address are its two subclasses; the factory methods return the right one.

Example: Creating and Inspecting Addresses

Addr.java▶ Try it
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
 
public class Addr {
    public static void main(String[] args) throws Exception {
        InetAddress loop = InetAddress.getLoopbackAddress();
        System.out.println(loop.getHostAddress()
            + " loopback? " + loop.isLoopbackAddress());
 
        InetAddress home = InetAddress.getByName("192.168.1.20");
        System.out.println(home.getHostAddress()
            + " private? " + home.isSiteLocalAddress());
        System.out.println(Arrays.toString(home.getAddress()));
        System.out.println("IPv4? " + (home instanceof Inet4Address));
 
        InetAddress raw = InetAddress.getByAddress(
            new byte[] {(byte) 203, 0, 113, 7});
        System.out.println(raw.getHostAddress()
            + " private? " + raw.isSiteLocalAddress());
 
        InetAddress v6 = InetAddress.getByName("::1");
        System.out.println(v6.getHostAddress() + " IPv6? "
            + (v6 instanceof Inet6Address)
            + " loopback? " + v6.isLoopbackAddress());
 
        InetSocketAddress endpoint =
            new InetSocketAddress("127.0.0.1", 8080);
        System.out.println(endpoint.getAddress().getHostAddress()
            + " port " + endpoint.getPort());
 
        System.out.println(InetAddress.ofLiteral("10.0.0.5").getHostAddress());
        try {
            InetAddress.getByName("no-such-host.invalid");
        } catch (UnknownHostException e) {
            System.out.println("UnknownHostException for a name"
                + " that doesn't exist");
        }
        try {
            InetAddress.ofLiteral("example.com");
        } catch (IllegalArgumentException e) {
            System.out.println("ofLiteral: " + e.getMessage());
        }
    }
}
Output
127.0.0.1 loopback? true
192.168.1.20 private? true
[-64, -88, 1, 20]
IPv4? true
203.0.113.7 private? false
0:0:0:0:0:0:0:1 IPv6? true loopback? true
127.0.0.1 port 8080
10.0.0.5
UnknownHostException for a name that doesn't exist
ofLiteral: Invalid IP address literal: example.com

Explanation:

  • Loopback (127.0.0.1, or ::1 in IPv6) always means "this computer".
  • getByName("192.168.1.20") is given an address, not a name, so it only parses the text. isSiteLocalAddress() is true because 192.168.x.x is a private range used inside homes and offices; so are 10.x.x.x and 172.16.x.x to 172.31.x.x.
  • The bytes print as -64, -88 because Java's byte is signed: 192 is stored as 192 - 256 = -64. That is also why building an address needs the cast (byte) 203.
  • InetSocketAddress is an address plus a port: one complete endpoint. Sockets and servers accept it directly.
  • getByName with a name that doesn't exist throws the checked UnknownHostException.
  • ofLiteral refuses anything that isn't an address, so it can never trigger a slow or unexpected DNS lookup. Use it when the text is supposed to be an IP address.

Looking Up Real Host Names

These calls need a network connection, and the answers depend on where and when you run them:

Lookup.java
InetAddress site = InetAddress.getByName("www.poolstring.com");
System.out.println(site.getHostAddress());
 
for (InetAddress a : InetAddress.getAllByName("www.poolstring.com")) {
    System.out.println(a);
}
 
System.out.println(InetAddress.getLocalHost());

A lookup blocks until DNS answers or gives up, which can take seconds. Java caches successful lookups (by default for 30 seconds), so repeating one is fast.

IPv4 and IPv6

PointIPv4IPv6
Size32 bits (4 bytes)128 bits (16 bytes)
Written as192.168.1.202001:db8:0:0:0:0:0:1, shortened to 2001:db8::1
Loopback127.0.0.1::1
Java classInet4AddressInet6Address

Code written against InetAddress works with both, so you rarely need the subclasses.

Common Mistakes

Calling new InetAddress(...). There is no public constructor.

Passing user input to getByName when you expect an IP address. It will do a DNS lookup on whatever text it gets. Use ofLiteral.

Forgetting that bytes are signed. Values above 127 need a cast, and print as negative numbers.

Using getLocalHost() to find "my IP address". A computer can have several addresses; this returns only the one for its host name.

Interview Corner

What is the InetAddress class used for?

It represents an IP address (IPv4 through Inet4Address, IPv6 through Inet6Address) and provides name resolution. It has no public constructors; instances come from static methods such as getByName(host), getAllByName(host), getLocalHost(), getLoopbackAddress() and getByAddress(bytes). Instance methods return the textual address, host name and raw bytes, and test for loopback, private or multicast addresses. InetSocketAddress pairs an InetAddress with a port.

Practice

  1. Easy: Print whether each of 10.1.2.3, 8.8.8.8 and 172.20.0.1 is a private (site-local) address.
  2. Harder: Write a method that takes a string and returns "IPv4", "IPv6" or "not an address", using InetAddress.ofLiteral.

Quick check: InetAddress

4 questions
1How do you create an InetAddress?
2What does getByName do when given a host name?
3Which address is the IPv4 loopback?
4What does InetSocketAddress add to an InetAddress?

Key Takeaways

Was this tutorial helpful?

Lesson 476 of 482