SoFunction
Updated on 2025-03-10

Java two ways to get native IP address

In Java programming, if there is a requirement for the IP address of the native machine, the editor will show you the method:

1. Use

The first is the most basic way to obtain the IP address of the machine.

Sample code:

import ;

import ;

public class GetIPAddress {

    public static void main(String[] args) {

        try {

            InetAddress inetAddress = ();

            ("Native IP address: " + ());

        } catch (UnknownHostException e) {

            ();

        }

    }

}

This method can work normally in most simple scenarios, but if the host has multiple network interfaces or is in a complex network environment, what you may get is not the expected one.IP address

2. Traversing the network interface to obtain

Get more accurate IP address information by traversing all network interfaces.

Sample code:

import ;

import ;

import ;

import ;



public class GetIPAddressByInterface {

    public static void main(String[] args) {

        try {

            Enumeration<NetworkInterface> networkInterfaces = ();

            while (()) {

                NetworkInterface networkInterface = ();

                Enumeration<InetAddress> inetAddresses = ();

                while (()) {

                    InetAddress inetAddress = ();

                    if (!() && ().indexOf(':') == -1) {

                        ("Native IP address: " + ());

                    }

                }

            }

        } catch (SocketException e) {

            ();

        }

    }

}

The above code first obtains all network interfaces, then traverses the IP addresses under each interface, excludes the loopback address (isLoopbackAddress judgment) and IPv6 address (judged by indexOf(':') == -1), thereby obtaining the possible native IP addresses. This method can obtain multiple IP addresses that meet the criteria in a complex network environment, and can be further filtered according to actual needs.

Through the above two methods, the IP address of the machine can be obtained in a Java program, and developers can choose the appropriate method to use according to the specific application scenario.

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