Javascript is required

Java 获取本机 IP 地址的方法

作者: IP66

栏目: 技术解读

发布时间: 2024-11-21 14:30:54

在 Java 编程中,若有本机的 IP 地址的需求,小编来展示一下方法:

一、使用 InetAddress.getLocalHost()

一是最基本的获取本机 IP 地址的方式。

示例代码:

import java.net.InetAddress;

import java.net.UnknownHostException;

 

public class GetIPAddress {

    public static void main(String[] args) {

        try {

            InetAddress inetAddress = InetAddress.getLocalHost();

            System.out.println("本机 IP 地址: " + inetAddress.getHostAddress());

        } catch (UnknownHostException e) {

            e.printStackTrace();

        }

    }

}

这种方法在大多数简单场景下可以正常工作,但如果主机有多个网络接口或者处于复杂的网络环境中,可能获取到的不是期望的 IP 地址。

二、遍历网络接口获取

通过遍历所有网络接口来获取更准确的 IP 地址信息。

示例代码:

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

 

public class GetIPAddressByInterface {

    public static void main(String[] args) {

        try {

            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {

                NetworkInterface networkInterface = networkInterfaces.nextElement();

                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();

                while (inetAddresses.hasMoreElements()) {

                    InetAddress inetAddress = inetAddresses.nextElement();

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

                        System.out.println("本机 IP 地址: " + inetAddress.getHostAddress());

                    }

                }

            }

        } catch (SocketException e) {

            e.printStackTrace();

        }

    }

}

上述代码首先获取所有网络接口,然后遍历每个接口下的 IP 地址,排除回环地址(isLoopbackAddress 判断)和 IPv6 地址(通过 indexOf(':') == -1 判断),从而得到可能的本机 IP 地址。这种方法在复杂网络环境中能获取到多个符合条件的 IP 地址,可根据实际需求进一步筛选。

通过以上两种方法,可以在 Java 程序中获取本机的 IP 地址,开发人员可根据具体的应用场景选择合适的方法使用。

相关推荐