You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何获取LAN或以太网IP地址?(无法使用EthernetManager)

获取以太网IP地址(无需EthernetManager)

如果无法使用EthernetManager,可以通过遍历系统中的网络接口来获取以太网的IP地址,核心思路是识别以太网对应的网络接口并提取其有效IPv4地址。

以下是实现代码:

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

public String getEthernetIpAddress() {
    try {
        // 遍历所有网络接口
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            
            // 跳过回环接口和未启用的接口
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            
            // 判断是否为以太网接口(常见命名为eth0、en0等)
            String interfaceName = networkInterface.getName();
            if (interfaceName.startsWith("eth") || interfaceName.startsWith("en")) {
                // 遍历该接口下的所有IP地址
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    // 排除IPv6地址,只取IPv4地址
                    if (!address.isLoopbackAddress() && address.getAddress().length == 4) {
                        return address.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null; // 未找到以太网IP时返回null
}

代码说明:

  • 通过NetworkInterface.getNetworkInterfaces()获取设备上所有的网络接口。
  • 跳过回环接口(如localhost)和未激活的接口,避免无效数据。
  • 借助接口名称前缀判断以太网接口(不同设备的以太网接口命名可能略有差异,eth或en是常见前缀)。
  • 遍历接口下的IP地址,筛选出非回环的IPv4地址并返回。

内容的提问来源于stack exchange,提问作者GNK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:40:39