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

刚好有个项目需要获取网络IP地址。由于设备可以连接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;
    }

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

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/39848a150e.html