Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java InetAddress Class
3.
TCP/IP Protocol
4.
What is an IP Address?
5.
IPv4
5.1.
Features
5.2.
Addressing Modes
5.2.1.
Unicast Addressing
5.2.2.
Broadcast Addressing
5.2.3.
Multicast Addressing
5.3.
Classes of the IPv4
5.3.1.
Class A
5.3.2.
Class B
5.3.3.
Class C
5.3.4.
Class D
5.3.5.
Class E
5.4.
Addresses Exhaustion
6.
IPv6
6.1.
Features
6.2.
Addressing Modes
6.2.1.
Unicast Addressing
6.2.2.
Multicast Addressing
6.2.3.
Anycast Addressing
7.
Name Resolution
8.
Methods of InetAddress Class
9.
Example 1
10.
Example 2
11.
Example 3
12.
Example 4
13.
Frequently Asked Questions
13.1.
What is the java.net package?
13.2.
What does the datagram packet class entail?
13.3.
Which method is used to compare two IP addresses?
13.4.
Which method of the InetAddress class is used to get the IP address of the computer?
14.
Conclusion
Last Updated: Mar 27, 2024
Easy

Java InetAddress Class

Author Nagendra
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java is one of the most popular programming languages. Learning Java reinforces essential computer science principles while providing access to a wide range of professional options. We use packages in Java to arrange classes and interfaces.
The Java InetAddress class is used to encapsulate the IP address.  Most other networking classes, such as SocketServerSocketURLDatagramSocketDatagramPacket, and others, use it. This blog discusses the Java’s InetAddress Class in detail, including IP addresses, their addressing modes, InetAddress Class methods, and examples. Without further ado, let's get started.

Must Read, Multithreading in java, Duck Number in Java

Java InetAddress Class

Java InetAddress class is used to represent the IP address. The InetAddress class contains methods for obtaining the IP address of any hostname, such as www.google.comwww.facebook.com, and so on. The IP address, including IPv4 and IPv6, are referred to by the InetAddress class. An IP address and, optionally, its matching hostname make up an instance of an InetAddress. An IP address is an unsigned 32-bit or 128-bit value. The InetAddress class is a cache that stores both successful and unsuccessful hostnames.

Let's first learn about the TCP/IP protocol, which is used for connecting network devices on the internet.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

TCP/IP Protocol

TCP/IP stands for Transmission Control Protocol/Internet Protocol. It is a set of communication protocols that are used to connect network devices on the Internet. TCP/IP is a protocol that governs data transfers between end-to-end internet connections. It specifies how it should be divided into packets, addressed, transferred, routed, and received at the intended location. In the suite, there are two core protocols that each serve a different purpose.

TCP defines how apps can build communication channels across a network. It also describes how a message is broken down into smaller packets before being sent across the Internet and how it is reassembled in the proper order at the destination address. 

IP refers to how each packet is addressed and routed to ensure it reaches its intended destination. This IP address is checked by the network's gateway computer to decide where the message should be forwarded. Let's discuss the IP Address in more detail in the next section.

What is an IP Address?

An IP address is a numerical representation of a network resource that uniquely identifies it. IP addresses are divided into two types: IPv4 and IPv6.

  • IPv4 addresses are 32 bits long, allowing for a total of 232 distinct addresses. 
  • IPv6 addresses are 128 bits long, resulting in 2128 unique addresses.

IP addresses are stated in binary numbers. However, they are usually expressed in decimal (IPv4) or hexadecimal (IPv6) to make them more human-readable.

IPv4

IPv4 addresses are 32 bits long and can include up to 4,294,967,296 distinct addresses. There are 232 addresses in the IPv4 protocol. IPv4 is a 32-bit binary number that contains two sub-addresses: the network and the host, separated by an imaginary boundary. An IP address is made up of four octets of decimal digits ranging from 0-255. An IPv4 address is written in dotted-decimal notation, with each eight-bit (octet) being represented by a number between 1 and 255, separated by a dot. The following is an example of an IPv4 address: 192.172.24.43.

Features

IPv4 has the following features:

  • IPv4 is a connectionless protocol.
  • The class-based addressing scheme uses less memory and makes it easy to recall addresses.
  • Video conferencing and libraries are also available.

 

Let's take a look at the different addressing modes of IPv4.

Addressing Modes

There are three different types of addressing modes supported by IPv4. They are as follows:

Unicast Addressing

In unicast addressing, only one intended host and destination will receive the data.

Broadcast Addressing

In broadcast addressing, all hosts in a network segment will get the packet.

Multicast Addressing

The Multicast Addressing mode is a hybrid of the two previous techniques. The server sends out packets that are received by multiple servers. The network has one IP address for the Network Number, which represents the whole network, and another IP address for the Broadcast address, which represents all of the hosts in that network.

Classes of the IPv4

There are five classes of IP ranges available with an IPv4 IP address: Class A, Class B, Class C, Class D, and Class E, albeit only A, B, and C are regularly used. A range of valid IP addresses is allowed for each class. Let's dive into the details of each one.

Class A

The first eight bits of a Class A network address indicate the network portion of the address, while the remaining bits represent the host portion of the address. There are 128 different Class A networks to choose from. The address range for Class A is 0.0.0.0 to 127.0.0.0.

Class B

The first 16 bits of a Class B network address indicate the network component of the address, while the remaining bits are referred to as the host part of the address. Its IP address ranges between 128.0.0.0 and 191.255.0.0. There are approximately 16,384 Class B networks in the United States.

Class C

The first 24 bits of a Class C network address indicate the network address, whereas the remaining bits constitute the host address. The network addresses for Class C range from 192.0.0.0 to 223.255.255.0. There are about 2 million Class C networks to choose from.

Class D

Multicasting applications are used in Class D networks. It has 32-bit network addresses that correspond to multicast groups in the 224.0.0.0 - 239.255.255.255 range. There are no host addresses in the Class D address space.

Class E

In Class E networks, addresses ranging from 240.0.0.0 to 255.255.255.255 are used. Because this class is reserved, its usage was never defined. As a result, the majority of network implementations consider these addresses to be invalid or undefined. The 255.255.255.255 address, which is used as a broadcast address, is an exception.

Addresses Exhaustion

The IPv4 specification was first created for the DARPA network. The 232 addresses were certainly thought to be sufficient at the time. It became clear that the IPv4 address space would be insufficient for a global Internet with multiple linked devices per user. Hence the IPv6 addresses are generated as a result of this.

IPv6

IPV6 built a massive address space for the network to circumvent the address space issue in technology. The address space expands from 32 bits to 128 bits, resulting in 3.4*1038 (2128) unique addresses, which is said to be enough to assign one to every atom on the planet's surface. Eight sets of four hexadecimal digits are specified in IPv6, each separated by a colon. In the IPv6 version, there are no defined classes. 

2001 : db8 : 3333 : 4444 : CCCC : DDDD : EEEE : FFFF is an IPv6 address.

Features

IPv6 has the following features:

  • It can be configured in both stateful and stateless modes.
  • It contributes to the improvement of service quality (QoS).
  • Its addressing and routing infrastructure is hierarchical.

Let's take a look at the different addressing modes of IPv6.

Addressing Modes

There are Three different types of addressing modes supported by IPv6. These are:

Unicast Addressing

The source and destination IP addresses make up an IPv6 packet. The host has a unique IP address in that network section. When a network router receives a unicast IP packet destined for a single host, it sends it out over one of its outgoing interfaces to that host.

Multicast Addressing

A particular multicast address is used to send packets to several hosts. All hosts with interest in the multicast information must first join the multicast group. All of the interfaces in that group receive and process the multicast packet, but other hosts who aren't interested in multicast packets ignore the information.

Anycast Addressing

The same Anycast IP address is assigned to several hosts. A Unicast message is sent when a host wants to communicate with another host that has an Anycast IP address. That Unicast message is delivered to the host that is nearest to the sender in terms of routing cost, thanks to the complicated routing process.

Name Resolution

It's quite impractical to remember the IP address of every device in both IPv4 and IPv6. The name resolution process converts an IP address into a human-readable computer domain name. The Domain Name Servers maintain a directory of domain names and convert them to IP addresses. Although domain names are simple to remember, IP addresses can be used to access websites. Your DNS connected with the domain name turns www.google.com into a machine-friendly IP address and directs your Internet connection to the proper website whenever a client types in www.google.com. It's time to learn about the different methods of Java InetAddress Class.

Methods of InetAddress Class

The methods of the InetAddress class are listed below.

Lets clear our concept by looking at various examples.

Example 1

The following example prints the localhost address of the computer system.

Code

import java.net.InetAddress;
class host
{
public static void main(String ar[])throws Exception
   {
   InetAddress address=InetAddress.getLocalHost();
   System.out.println(address);
   }
}

Output

168.142.72.38

Explanation

The program prints the localhost address of the system.

Example 2

This example lists all the IP addresses that are associated with a given hostname.

Code

import java.net.InetAddress;
class host
{
public static void main(String ar[])throws Exception
   {
   InetAddress[] address=InetAddress.getAllByName("google.com");
   for(InetAddress addr:address)
   System.out.println(addr.getHostAddress());
   }
}

Output

142.251.6.100
142.251.6.101
142.251.6.139
142.251.6.138
142.251.6.113
142.251.6.102

Explanation

The program displays all IP addresses associated with google.com.

Example 3

The following example explains the usage of various methods of InetAddress Class.

Code

import java.net.InetAddress;
public class host {
    public static void main(String ar[])
    {
         try
         {
             InetAddress addr=InetAddress.getLoopbackAddress();
             //prints the loopback address
             System.out.println("The loopback address"+addr.getHostAddress()); 
             
             byte[] hashC=new byte[]{127,1,0,0};
             //Prints hashcode for the object
            System.out.println("Hashcode :"+hashC.hashCode());
            
            InetAddress addF=InetAddress.getByName("www.facebook.com");
            //Checks InetAddress represents local address or not
             System.out.println("local address or not:="+addF.isAnyLocalAddress()); 
             
             InetAddress addY=InetAddress.getByName("www.yahoo.com");
              //Checks address is a link local address
             System.out.println("link local address or not: "+addY.isLinkLocalAddress());
             
             InetAddress addC=InetAddress.getByName("www.twitter.com");
             // Checks that multicast address has a global scope or not
            System.out.println("multicast address has global scope or not: "+addC.isMCGlobal()); 
            
             InetAddress addG=InetAddress.getByName("www.google.com");
             // Checks the utility routine if the multicast address has link scope or not.
            System.out.println("multicast address has link scope or not: "+addG.isMCLinkLocal()); 
            
            InetAddress addJ=InetAddress.getByName("www.codingninjas.com");
            //Checks the utility routine if the multicast address has node scope or not
            System.out.println("multicast address has node scope or not: "+addJ.isMCNodeLocal()); 
            
            InetAddress addt=InetAddress.getByName("www.codingninjas.com");
            //Checks the utility routine if the multicast address has organization scope or not.
            System.out.println("multicast address has organization scope or not: "+addt.isMCOrgLocal()); 
         }
         catch(Exception e)
         {
             System.out.println(e);
         }
    }
}

Output

The loopback address 127.0.0.1
Hashcode :1160460865
local address or not:=false
link local address or not: false
multicast address has global scope or not: false
multicast address has link scope or not: false
multicast address has node scope or not: false
multicast address has organization scope or not: false

Explanation

The usage of various methods of InetAddress Class is implemented in the above code snippet.

Example 4

This example explains the comparison between two IP addresses using equals() method.

Code

import java.net.InetAddress;
public class host {
    public static void main(String ar[])
    {
        try
        {
            InetAddress ip1_add=InetAddress.getByName("www.google.com");
            System.out.println("Host 1 :"+ip1_add.getHostName());
            InetAddress ip2_add=InetAddress.getByName("www.google.com");
            System.out.println("Host 2 :"+ip2_add.getHostName());
            if(ip1_add.equals(ip2_add))
            {
                System.out.println("They are equal");
            }
            else
            {
                System.out.println("They are not equals");
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
 }

Output

Host 1 :www.google.com
Host 2 :www.google.com
They are equal

Explanation

The IP addresses of each host are compared using the equals() method. The output “They are equal” is printed since both represent the same IP address.

Also see, Hashcode Method in Java

Frequently Asked Questions

What is the java.net package?

The java.net package includes DatagramPacket objects that can be sent and received over the network using a DatagramSocket object.

What does the datagram packet class entail?

A datagram packet is represented by the Java DatagramPacket class. It's used to construct a connectionless packet delivery service, in which each message is routed from one machine to another based on the information contained within it.

Which method is used to compare two IP addresses?

The equals() method is used to compare two IP addresses.

Which method of the InetAddress class is used to get the IP address of the computer?

The getLocalHost() method is used to get the IP address of the computer.

Conclusion

In this article, we have extensively discussed the InetAddress Class in Java along with the details of its methods, IP address, their addressing modes, and examples.
We hope that this blog has helped you enhance your knowledge regarding the InetAddress Class in Java, and if you would like to learn more, check out our articles on Java. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Do upvote our blog to help other ninjas grow. Happy Coding!!

Previous article
DatagramPacket and DatagaramSocket in Java
Next article
Server Socket Class in Java
Live masterclass