Java Networking – inetAddress
In Java, InetAddress
is a class that represents an IP address and provides methods to work with IP addresses and hostnames. It is part of the java.net
package and is used in network programming for tasks such as resolving hostnames, retrieving IP addresses, and performing network-related operations. Here’s an overview of InetAddress
in Java networking but before lets see Java.Net Package first.
Java.Net Package
The java.net
package in Java provides classes and interfaces for network programming. It offers a wide range of functionalities to create networked applications, interact with network protocols, perform network operations, and handle communication over the network. Here’s an overview of some important classes and interfaces in the java.net
package:
URL
: TheURL
class represents a Uniform Resource Locator and provides methods to work with URLs. It allows you to create, parse, and manipulate URLs, and provides access to different components of a URL, such as the protocol, host, port, path, query parameters, and more.URLConnection
: TheURLConnection
class represents a connection to a resource specified by a URL. It provides methods to establish a connection, read data from the resource, write data to the resource, handle request properties, and access response headers.InetAddress
: TheInetAddress
class represents an IP address and provides methods to work with IP addresses and hostnames. It allows you to resolve hostnames to IP addresses and vice versa, obtain the IP address of the local machine, check reachability, and more.Socket
andServerSocket
: TheSocket
class represents a client-side endpoint of a connection, while theServerSocket
class represents a server-side endpoint. These classes are used for creating client-server applications and allow communication over TCP/IP. They provide methods to establish connections, send and receive data, handle timeouts, and manage socket options.DatagramSocket
andDatagramPacket
: TheDatagramSocket
class is used for connectionless communication using the UDP (User Datagram Protocol). It allows sending and receiving datagram packets, which are small units of data. TheDatagramPacket
class encapsulates the data and addressing information for the packet.SocketTimeoutException
: This exception is thrown when a socket operation times out due to a specified timeout value. It is commonly used to handle situations where a socket connection or operation takes longer than expected.URI
: TheURI
class represents a Uniform Resource Identifier and provides methods to work with URIs. It allows you to create, parse, and manipulate URIs, and provides access to different components of a URI, such as the scheme, authority, path, query, and fragment.URLDecoder
andURLEncoder
: These utility classes provide methods to decode and encode URL-encoded strings, respectively. They are useful for handling special characters and ensuring proper encoding of URLs.
These are just a few examples of the classes and interfaces provided by the java.net
package. The package also includes classes for working with proxy servers, handling network interfaces, performing network-related operations (such as pinging), and more. The java.net
package is an essential part of network programming in Java, enabling developers to build networked applications, interact with network protocols, and perform various network operations.
Here’s an overview of InetAddress
in Java networking
IP Address Representation:
The InetAddress
class represents an IP address, which can be either an IPv4 address (e.g., 192.0.2.1) or an IPv6 address (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334). The InetAddress
class provides methods to obtain the address in both textual and byte array formats.
Example
InetAddress ip= InetAddress.getByName(“www.examradar.com”);System.out.println(“ip:”+ip);
Output:
Ip: examradar.com./166.62.27.173
Resolving Hostnames:
The InetAddress
class offers methods to resolve hostnames to IP addresses and vice versa. The getByName()
method takes a hostname as input and returns an InetAddress
object representing the IP address corresponding to that hostname. Conversely, the getHostName()
method retrieves the hostname associated with an InetAddress
object.
Lets check below example
import java.io.*; import java.net.*; public class getipofhost { public static void main(String[] args) throws Exception { InetAddress ip = InetAddress.getByName("www.examradar.com"); System.out.println("IP: "+ip); } }
IP: www.examradar.com/166.62.27.173
LocalHost:
The InetAddress
class provides a static method called getLocalHost()
that returns the InetAddress
object representing the current machine’s IP address or hostname. This method is often used to determine the IP address or hostname of the local machine.
InetAddres : Method
Method | Description |
Public static inetAddress getLocalHost() through UnknownHostException | Returns the address of the local host |
Lets check below example
import java.io.*; import java.net.*; public class getipofhost { public static void main(String[] args) throws Exception { InetAddress ip = InetAddress.getLocalHost(); System.out.println("LocalHost: "+ip); } }
LocalHost: user-PC/192.168.225.32
InetAddres : Method
Method | Description |
Public string getHostName() through UnknownHostException | It returns the hostname of the IP Address |
Let’s check below example:
import java.io.*; import java.net.*; public class getipofhost { public static void main(String[] args) throws Exception { InetAddress ip = InetAddress.getByName(“192.168.225.32”); System.out.println(“HostName: “+ip.getHostName()); } }
HostName: user-PC
InetAddres : Method
Method | Description |
Public string getHostAddress() | It returns the IP Address in string formate |
Lets check below example:
import java.io.*; import java.net.*; public class getipofhost { public static void main(String[] args) throws Exception { InetAddress ip = InetAddress.getByName("www.examradar.com"); System.out.println("HostAddress: "+ip.getHostAddress()); } }
HostAddress: 166.62.27.173
Other Methods of inetAddress
Method | Description |
string toString() | Converts the IP address to String formate |
boolean equal(Object obj) | Compares this object against specified object |
Static InetAddress[] getAllByName(String host) | Returns an array of its IP addresses ,based on configured name service on the system |
Static InetAddress[] getLoopbackAddress() | Returns loopback address |
Multiple IP Addresses:
In some cases, a single hostname can be associated with multiple IP addresses. The getAllByName()
method allows retrieving an array of InetAddress
objects representing all the IP addresses associated with a given hostname.
Utility Methods:
The InetAddress
class provides additional utility methods, such as isReachable()
to check if a remote IP address is reachable, isLoopbackAddress()
to determine if an IP address represents the loopback address (localhost), and isAnyLocalAddress()
to check if an IP address represents any local address.
Example usage of InetAddress
:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample {
public static void main(String[] args) {
try {
// Resolving hostname to IP address
InetAddress address = InetAddress.getByName("www.example.com");
System.out.println("IP Address: " + address.getHostAddress());
// Resolving IP address to hostname
InetAddress address2 = InetAddress.getByName("192.0.2.1");
System.out.println("Hostname: " + address2.getHostName());
// Getting the IP address of the local machine
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localAddress.getHostAddress());
System.out.println("Local Hostname: " + localAddress.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
The InetAddress
class in Java provides a convenient way to work with IP addresses and hostnames in network programming. It allows developers to resolve hostnames, retrieve IP addresses, and perform other network-related tasks in their Java applications.