How to Retrieve the Current Machine's IP Address in Java?

Question

How to retrieve the current machine's IP address in Java?

public class IPAddressRetriever {
    public static void main(String[] args) throws Exception {
        enumerationNetworkInterfaces();
    }

    public static void enumerationNetworkInterfaces() throws Exception {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                System.out.println(inetAddress.getHostAddress());
            }
        }
    }
}

Answer

Retrieving the current machine's IP address in Java can be essential for networking applications. This guide will help you distinguish between local and public IP addresses for various use cases.

import java.net.*;
import java.util.*;

public class IPAddressRetriever {
    public static void main(String[] args) throws Exception {
        enumerationNetworkInterfaces();
    }

    public static void enumerationNetworkInterfaces() throws Exception {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                String ip = inetAddress.getHostAddress();
                // Check if it's a loopback address or a private address
                if (inetAddress.isLoopbackAddress()) {
                    System.out.println("Loopback IP: " + ip);
                } else if (inetAddress instanceof Inet4Address && !networkInterface.isVirtual()) {
                    System.out.println("Public or LAN IP: " + ip);
                }
            }
        }
    }
}

Causes

  • Local IP addresses are often returned instead of public IPs by default methods.
  • Multiple network interfaces can be present on a machine, complicating IP retrieval.

Solutions

  • Use the `NetworkInterface` class to enumerate all network interfaces and their associated IP addresses.
  • Identify the desired IP address based on your criteria (PPP, LAN, or localhost).

Common Mistakes

Mistake: Assuming InetAddress.getLocalHost() will always return the public IP address.

Solution: Use NetworkInterface.getNetworkInterfaces() to get all network interfaces and filter by desired IP type.

Mistake: Not distinguishing between local and public IPs.

Solution: Explicitly check networkInterface.isVirtual() and address types such as isLoopbackAddress() for filtering.

Helpers

  • Java IP address retrieval
  • get machine IP address Java
  • NetworkInterface Java
  • public and local IP in Java
  • Socket connection Java

Related Questions

⦿How to Resolve GSON's "Expected BEGIN_OBJECT but was BEGIN_ARRAY" Exception?

Learn how to fix GSONs Expected BEGINOBJECT but was BEGINARRAY error when parsing JSON arrays in Java. Find stepbystep solutions and code examples

⦿What is the Performance Impact of Variable Declarations Inside vs. Outside a Loop in Java?

Explore the performance implications of declaring variables before or inside loops in Java. Understand their differences and best practices.

⦿Understanding the Maximum Value of Integers in C and Java

Discover the differences in maximum integer values between C and Java despite both using 32 bits. Learn about data types and their ranges.

⦿How to Replace Multiple Spaces with a Single Space and Trim Leading/Trailing Spaces in Java

Learn how to replace multiple spaces with a single space and trim leadingtrailing spaces in Java strings with examples.

⦿Why Are Interface Variables Static and Final by Default in Java?

Discover why interface variables in Java are static and final by default including the implications and benefits of this design.

⦿Maven Error: Unable to Read Artifact Descriptor for Dependency

Learn how to resolve the Maven error Failed to read artifact descriptor when building your project by understanding common causes and solutions.

⦿Understanding the Purpose of Optional.of vs Optional.ofNullable in Java

Explore the differences between Optional.of and Optional.ofNullable in Java 8 and understand when to use each properly.

⦿How to Resolve Java Error in Flutter Doctor When Accepting Android Licenses

Learn how to fix the java.lang.NoClassDefFoundError in Flutter when running flutter doctor androidlicenses.

⦿How to Retrieve the Full Path of the src/test/resources Directory in JUnit

Learn how to find the path of the srctestresources directory in JUnit tests with practical code examples and common pitfalls.

⦿How to Determine if Two Lists Contain Exactly the Same Elements in Java?

Learn how to check if two Java Lists have the same elements in order using standard libraries. Detailed explanation and code examples included.

© Copyright 2025 - CodingTechRoom.com

close