1. Home
  2. Docs
  3. Network Programming
  4. Internet Address
  5. The InetAddress Class

The InetAddress Class

InetAddress Class

  • InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com, etc.
  • An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name.
    There are two types of addresses: Unicast and Multicast.
    • Unicast is an identifier for a single interface
    • Multicast is an identifier for a set of interfaces.
  • Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions.
  • There are no public constructors in the InetAddress class. Instead, InetAddress has static factory methods that connect to a DNS server to resolve a hostname. The most common is InetAddress.getByName().

IP Address

  • An IP address helps to identify a specific resource on the network using a numerical representation.
  • Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge among the destination and the source.
  • Versions of IP
    • IPV4
    • IPV6

IPV4

  • IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is more than 4 million addresses.
  • Features of IPv4:
    • It is a connectionless protocol.
    • It utilizes less memory and the addresses can be remembered easily with the class based addressing scheme.
    • It also offers video conferencing and libraries.

IPV6

  • IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with a name IPng (Internet Protocol next generation).
  • Features of IPv6:
    • It has a stateful and stateless both configurations.
    • It provides support for quality of service (QoS).
    • It has a hierarchical addressing and routing infrastructure.

TCP/IP Protocol

  • TCP/IP is a communication protocol model used connect devices over a network via internet.
  • TCP/IP helps in the process of addressing, transmitting, routing and receiving the data packets over the internet.
  • The two main protocols used in this communication model are:
    • TCP i.e. Transmission Control Protocol. TCP provides the way to create a communication channel across the network. It also helps in transmission of packets at sender end as well as receiver end.
    • IP i.e. Internet Protocol. IP provides the address to the nodes connected on the internet. It uses a gateway computer to check whether the IP address is correct and the message is forwarded correctly or not.

InetAddress Methods

MethodsDescriptions
public static InetAddress getByName(String host) throws UnknownHostExceptionIt returns the instance of InetAddress containing LocalHost IP and name.
public static InetAddress getLocalHost() throws UnknownHostExceptionIt returns the instance of InetAdddress containing local host name and address.
public String getHostName()It returns the host name of the IP address.
public String getHostAddress()It returns the IP address in string format.
Java InetAddress Class Methods

Creating new InetAddress Objects

There are no public constructors in the InetAddress class. Instead, InetAddress has static factory methods that connect to a DNS server to resolve a hostname. The most common is InetAddress.getByName().

InetAddress address = InetAddress.getByName("www.chandanbhagat.com.np");

Caching

We know that DNS lookups can be expensive (in terms of the order of several seconds for a request that has to go through several intermediate servers, or one that’s trying to resolve an unreachable host) the InetAddress class caches the results of lookups. Once it gets the address of a host that was provided, it won’t look it up again, even if we create a fresh new InetAddress object for the same host. There wont be any of the problem as long as IP addresses don’t change while the program is running.

Negative results (host not found errors) are slightly more problematic. It’s not uncommon for an initial attempt to resolve a host to fail, but the immediately following one to succeed. The first attempt timed out while the information was still in transit from the remote DNS server. Then the address arrived at the local server and was immediately available for the next request. For this reason, Java only caches unsuccessful DNS queries for 10 seconds.

These times can be controlled by the system properties networkaddress.cache.ttl and networkaddress.cache.negative.ttl. The first of those, networkad dress.cache.ttl, specifies the number of seconds a successful DNS lookup will remain in Java’s cache. networkaddress.cache.negative.ttl is the number of seconds an unsuccessful lookup will be cached. Attempting to look up the same host again within these limits will only return the same value. Negative 1 is interpreted as “never expire.”

Besides local caching inside the InetAddress class, the local host, the local domain name server, and other DNS servers elsewhere on the Internet also cache the results of various queries. Java provides no way to control this. As a result, it may take several hours for the information about an IP address change to propagate across the Internet. In the meantime, your program may encounter various exceptions, including UnknownHostException, NoRouteToHostException, and ConnectException, depending on the changes made to the DNS.

Lookups by IP Address

Example Codes

InetDemo

package Chapter2;

import java.net.*;

public class InetDemo {
    public static void main(String[] args) {
        try {
            InetAddress ip = InetAddress.getByName("chandan.local");

            System.out.println("Host Name: " + ip.getHostName());
            System.out.println("IP Address: " + ip.getHostAddress());
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

InetDemo2

package Chapter2;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.util.Arrays;
import java.net.InetAddress;

public class InetDemo2 {
    public static void main(String[] arg) throws Exception {
        InetAddress ip = Inet4Address.getByName("localhost");
        InetAddress ip1[] = InetAddress.getAllByName("localhost");
        byte addr[] = { 72, 3, 2, 12 };
        System.out.println("ip : " + ip);
        System.out.print("\nip1 : " + ip1);
        InetAddress ip2 = InetAddress.getByAddress(addr);
        System.out.print("\nip2 : " + ip2);
        System.out.print("\nAddress : " + Arrays.toString(ip.getAddress()));
        System.out.print("\nHost Address : " + ip.getHostAddress());
        System.out.print("\nisAnyLocalAddress : " + ip.isAnyLocalAddress());
        System.out.print("\nisLinkLocalAddress : " + ip.isLinkLocalAddress());
        System.out.print("\nisLoopbackAddress : " + ip.isLoopbackAddress());
        System.out.print("\nisMCGlobal : " + ip.isMCGlobal());
        System.out.print("\nisMCLinkLocal : " + ip.isMCLinkLocal());
        System.out.print("\nisMCNodeLocal : " + ip.isMCNodeLocal());
        System.out.print("\nisMCOrgLocal : " + ip.isMCOrgLocal());
        System.out.print("\nisMCSiteLocal : " + ip.isMCSiteLocal());
        System.out.print("\nisMulticastAddress : " + ip.isMulticastAddress());
        System.out.print("\nisSiteLocalAddress : " + ip.isSiteLocalAddress());
        System.out.print("\nhashCode : " + ip.hashCode());
        System.out.print("\n Is ip1 == ip2 : " + ip.equals(ip2));
    }
}
Was this article helpful to you? Yes No

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *