小工具知识网

当前位置: 首页 > 行业知识 > Android 获取IP地址(有线和无线网络IP地址)

行业知识

Android 获取IP地址(有线和无线网络IP地址)

2026-11-08 04:08:09 来源:互联网转载

刚好有个项目需要获取网络IP地址。由于设备index.php/tags-653.html" >可以连接wifi,也可以连接有线网络。特此做个获取IP地址的笔记,代码如下:

// 获取ip地址private String getLocalIpAddress() {        ConnectivityManager netManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);        NetworkInfo info = netManager.getActiveNetworkInfo();                // 网络是否连接        if (info != null && info.isConnected()) {        // wifi类型            if (info.getType() == TYPE_WIFI) {                return getWifiIpAddress();            } else {            // 其他类型                return getEthIpAddress();            }        }        return "0.0.0.0";    }

获取WiFi的ip地址

// 获取wifi的ip地址private String getWifiIpAddress() {        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);        WifiInfo wifiInfo = wifiManager.getConnectionInfo();                // 获取32位整型IP地址        int ipAddress = wifiInfo.getIpAddress();        //返回整型地址转换成“*.*.*.*”地址        return String.format("%d.%d.%d.%d",                (ipAddress & 0xff), (ipAddress >> 8 & 0xff),                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));    }

获取有线网络的ip4地址

// 获取有线网络的ip4地址    private String getEthIpAddress() {        String infaceName = "eth0";        String ip = "0.0.0.0";        try {            Enumeration netInterface = NetworkInterface.getNetworkInterfaces();            while (netInterface.hasMoreElements()) {                NetworkInterface inface = netInterface.nextElement();                if (!inface.isUp()) {                    continue;                }// eth0 有线网络判断                if (!infaceName.equals(inface.getDisplayName())) {                    continue;                }                Enumeration netAddressList = inface.getInetAddresses();                while (netAddressList.hasMoreElements()) {                    InetAddress inetAddress = netAddressList.nextElement();                    // 获取IP4地址                    if (inetAddress instanceof Inet4Address) {                        return inetAddress.getHostAddress();                    }                }            }        } catch (Exception e) {        }        return ip;    }

如果对您有帮忙,请点赞支持。如有不合理的地方,请指正!谢谢~

上一篇:java.net.SocketException:Connection reset

下一篇:oa英语怎么读音发音?