Android获取本地IP地址-WIFI or 3G

/**
     * 获取终端IP地址
     * @return
     */
    public static String getLocalIpAddress(){ 
        try{ 
             for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
                 NetworkInterface intf = en.nextElement();   
                    for (Enumeration<InetAddress> enumIpAddr = intf   
                            .getInetAddresses(); enumIpAddr.hasMoreElements();) {   
                        InetAddress inetAddress = enumIpAddr.nextElement();   
                        if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {   
                            return inetAddress.getHostAddress().toString();   
                        } 
                        /*if (!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()) { 
                        System.out.println("--inetAddress---="+inetAddress.getHostAddress().toString());
                         return inetAddress.getHostAddress().toString(); */
                    }   
             } 
        }catch (SocketException e) { 
            // TODO: handle exception 
            System.out.println("WifiPreference IpAddress---error-" + e.toString()); 
        } 
        return null;  

    } 

 附件权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
<uses-permission android:name="android.permission.INTERNET"/>


### 如何获取可用的IP地址 #### 方法概述 为了找到可用的 IP 地址,可以通过多种方法实现。这些方法可以分为基于命令行工具、编程接口以及正则表达式的验证等方式。 --- #### 基于 Android 平台的方法 在 Android 中,可以通过以下几种方式来获取当前设备上的 IP 地址: 1. **通过 ADB Shell 获取** 使用 `adb shell` 工具可以直接查看设备的网络配置信息,包括无线和有线网络的 IP 地址。 ```bash adb shell ifconfig ``` 这条命令会返回详细的网络接口信息,从中可以解析出有效的 IP 地址[^1]。 2. **通过代码获取 WiFi 或有线网络的 IP 地址** 可以利用 Android 提供的 API 来获取连接到特定网络(WiFi 或有线)的 IP 地址: ```java WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int ipAddress = wifiMgr.getConnectionInfo().getIpAddress(); String formattedIp = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); System.out.println("WiFi IP Address: " + formattedIp); ``` 3. **获取所有网络节点的 IP 和 MAC 地址** 如果需要更全面的信息,还可以枚举所有的网络接口并提取其对应的 IP 地址和子网掩码等数据: ```java List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { System.out.println("Device Name: " + intf.getName()); System.out.println("IP Address: " + addr.getHostAddress()); } } } ``` 4. **检测热点模式下的 IP 地址** 当设备处于热点状态时,也可以通过类似的逻辑获取分配给客户端的 IP 地址范围: ```java DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo(); if (dhcpInfo != null && dhcpInfo.gateway != 0) { String gatewayIp = String.format( "%d.%d.%d.%d", dhcpInfo.gateway & 0xFF, (dhcpInfo.gateway >> 8) & 0xFF, (dhcpInfo.gateway >> 16) & 0xFF, (dhcpInfo.gateway >> 24) & 0xFF ); System.out.println("Gateway IP Address: " + gatewayIp); } ``` --- #### 正则表达式匹配有效 IP 地址 对于从网页或其他文本源中提取的有效 IP 地址,可以使用 Python 的正则表达式库来进行筛选。以下是具体的实现过程: 1. 定义一个用于匹配 IPv4 地址的正则表达式: ```python import re ip_pattern = r"(?:\d{1,3}\.){3}\d{1,3}" valid_ip_regex = re.compile(ip_pattern) test_string = "<td>192.168.1.1</td><td>不可用</td>" matches = valid_ip_regex.findall(test_string) print(matches) # 输出 ['192.168.1.1'] ``` 2. 结合 `<td>` 标签提取目标字段中的 IP 地址: ```python line_re = re.compile(r'(?:td>)(.+)(?:</td>)') extracted_data = line_re.search("<td>192.168.1.1</td>").group(1) print(extracted_data) # 输出 '192.168.1.1' ``` 3. 验证是否为合法的 IP 地址: 对提取的结果进一步过滤,排除不符合标准格式的数据: ```python def is_valid_ipv4(ip): parts = ip.split('.') if len(parts) != 4: return False for part in parts: try: value = int(part) if not (0 <= value <= 255): return False except ValueError: return False return True filtered_ips = [ip for ip in matches if is_valid_ipv4(ip)] print(filtered_ips) # 输出符合条件的 IP 列表 ``` --- #### 测试 IP 是否可用 要确认某个 IP 地址是否实际可访问,通常采用如下策略之一: 1. 发送 HTTP 请求至指定的目标 URL,并设置超时时间为合理值(如 3 秒)。如果请求成功,则说明该 IP 是可达的;否则视为无效。 ```python import requests url_template = "http://{}" target_ip = "192.168.1.1" timeout_seconds = 3 try: response = requests.get(url_template.format(target_ip), timeout=timeout_seconds) if response.status_code == 200: print(f"{target_ip} is reachable.") except Exception as e: print(f"{target_ip} is unreachable or timed out.") ``` 2. 访问专门提供反向查询服务的站点(例如 http://ip.chinaz.com/getip.aspx),以此间接判断目标主机的状态[^2]。 --- #### Qt 应用程序中的解决方案 在 Qt 开发环境中,同样能够方便地检索本地机器的所有网络适配器及其关联属性。下面展示了一个简单的例子,演示如何打印每张网卡的相关参数: ```cpp #include <QCoreApplication> #include <QNetworkInterface> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString allInfo; QList<QNetworkInterface> networkinterfaceList = QNetworkInterface::allInterfaces(); for (const auto &networkinterface : qAsConst(networkinterfaceList)) { allInfo += "设备名称:" + networkinterface.humanReadableName() + "\n"; allInfo += "硬件地址:" + networkinterface.hardwareAddress() + "\n"; const QList<QNetworkAddressEntry> addressentrylist = networkinterface.addressEntries(); for (const auto &entryip : qAsConst(addressentrylist)) { allInfo += "IP地址:" + entryip.ip().toString() + "\n"; allInfo += "子网掩码:" + entryip.netmask().toString() + "\n"; allInfo += "广播地址:" + entryip.broadcast().toString() + "\n"; } } qDebug() << allInfo; return a.exec(); } ``` 此段代码展示了如何遍历所有网络接口,并收集它们各自的 IP 地址、子网掩码以及其他重要细节[^3]。 --- #### 总结 以上介绍了不同平台和技术栈下获取及验证可用 IP 地址的具体手段。无论是移动应用开发还是桌面软件设计场景,都可以依据需求选取合适的方案加以实施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值