How to obtain an IP address in Java?

In Java, you can use the InetAddress class to obtain an IP address.

Here are some example codes:

  1. Obtain the local IP address:
import java.net.InetAddress;

public class Main {
    public static void main(String[] args) {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            System.out.println("本机IP地址: " + localhost.getHostAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. Obtain the IP address of a specified domain name:
import java.net.InetAddress;

public class Main {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getByName("www.google.com");
            System.out.println("www.google.com 的IP地址: " + address.getHostAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: The InetAddress.getLocalHost() method may return the IPv6 address of the local machine instead of the IPv4 address. If you need to retrieve the IPv4 address, you can use the NetworkInterface class to retrieve the local machine’s network interface and then obtain the IPv4 address from there.

For example:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class Main {
    public static void main(String[] args) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {
                        System.out.println("本机IPv4地址: " + address.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
bannerAds