SoFunction
Updated on 2025-05-15

Several common ways to obtain native IP in Java

There are many ways to get local IP addresses in Java. Here are a few common methods:

1. Use the InetAddress class

InetAddressClasses are classes used in the Java standard library to represent IP addresses, and you can obtain the IP address of the local host.

import ;
import ;

public class Main {
    public static void main(String[] args) {
        try {
            InetAddress localHost = ();
            ("Local IP Address: " + ());
        } catch (UnknownHostException e) {
            ();
        }
    }
}

2. Use the NetworkInterface class

NetworkInterfaceThe class provides finer-grained network interface information, which can obtain the IP addresses of all network interfaces.

import ;
import ;
import ;
import ;

public class Main {
    public static void main(String[] args) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = ();
            while (()) {
                NetworkInterface networkInterface = ();
                Enumeration<InetAddress> inetAddresses = ();
                while (()) {
                    InetAddress inetAddress = ();
                    if (!() && ()) {
                        ("Local IP Address: " + ());
                    }
                }
            }
        } catch (SocketException e) {
            ();
        }
    }
}

3. Use third-party libraries (such as Apache Commons Net)

If you need more complex features, you can use third-party libraries such asApache Commons Net

import ;
import ;
import ;

public class Main {
    public static void main(String[] args) {
        try {
            InetAddress localHost = ();
            ("Local IP Address: " + ());
        } catch (UnknownHostException e) {
            ();
        }
    }
}

How to choose when using it?

  • InetAddresskind: Simple and easy to use, suitable for most scenarios, especially when you only need to obtain the IP address of the local host.
  • NetworkInterfacekind: Suitable for scenarios where you need to obtain the IP addresses of all network interfaces, or you need to filter specific types of IP addresses (such as non-loopback addresses, local addresses, etc.).
  • Third-party library: Suitable for scenarios that require more complex network operations, such as subnet computing, IP address range processing, etc.

Summarize

For most simple scenarios, use()It is the easiest and direct way. If you need more granular control or handling multiple network interfaces, you can useNetworkInterfacekind.

This is the end of this article about several common methods for obtaining native IP in Java. For more related Java content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!