Javatpoint Logo
Javatpoint Logo

Get Local IP Address in Java

In Java, there are various scenarios where obtaining the local IP address of a machine is crucial. Whether it's for network configuration, socket programming, or server setups, knowing the local IP address is fundamental. In this section, we will explore different approaches to acquire the local IP address using Java.

Method 1: Using InetAddress Class

The java.net.InetAddress class provides a simple yet effective way to retrieve the local IP address. Here's an example of how to use it:

File Name: LocalIPAddressExample.java

Output:

Local IP Address: 192.168.1.10

The getLocalHost() method of the InetAddress class returns the local host address, which represents the IP address of the current machine. The getHostAddress() method retrieves the textual representation of the IP address. This method is suitable for most general use cases.

Method 2: Using NetworkInterface Class

Java's java.net.NetworkInterface class provides more advanced capabilities for network-related operations. By iterating over the available network interfaces, you can obtain the IP addresses associated with each interface. Here's an example:

File Name: LocalIPAddressExample.java

Output:

Local IP Address: 192.168.1.10
Local IP Address: 10.0.0.2

In this example, we retrieve all available network interfaces using the getNetworkInterfaces() method. Then, we iterate over each interface and obtain the associated IP addresses using the getInetAddresses() method. We filter out loopback addresses (isLoopbackAddress()) and focus only on IPv4 addresses (instanceof Inet4Address).

Note: The output may vary depending on your network configuration. In the examples above, the local IP address is displayed as 192.168.1.10 for Method 1 and both 192.168.1.10 and 10.0.0.2 for Method 2. The code will list all available IPv4 addresses associated with non-loopback network interfaces.

Conclusion:

Obtaining the local IP address in Java is crucial for various networking tasks. The InetAddress class and the NetworkInterface class provide different approaches to accomplish this. By using InetAddress.getLocalHost(), you can quickly retrieve the local IP address. Alternatively, by iterating over the available network interfaces using NetworkInterface.getNetworkInterfaces(), you can access more detailed information about each network interface and their associated IP addresses.

Remember to handle exceptions, such as UnknownHostException and SocketException, when implementing these approaches in your code. With the acquired local IP address, you can confidently proceed with your network-related tasks in Java.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA