public static String getIpAddress(Context context){ NetworkInfo info = ((ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 3/4g网络 if (info.getType() == ConnectivityManager.TYPE_MOBILE) { 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() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) { // wifi网络 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ipAddress = intIP2StringIP(wifiInfo.getIpAddress()); return ipAddress; } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET){ // 有限网络 return getLocalIp(); } } return null; } private static String intIP2StringIP(int ip) { return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF); } // 获取有限网IP private static String getLocalIp() { 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() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException ex) { } return "0.0.0.0"; } public static String getMacAddressFromIp(Context context) { String mac_s= ""; StringBuilder buf = new StringBuilder(); try { byte[] mac; NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName(getIpAddress(context))); mac = ne.getHardwareAddress(); for (byte b : mac) { buf.append(String.format("%02X:", b)); } if (buf.length() > 0) { buf.deleteCharAt(buf.length() - 1); } mac_s = buf.toString(); } catch (Exception e) { e.printStackTrace(); } return mac_s; }
Android 获取ip地址和mac地址
最新推荐文章于 2024-02-04 16:01:12 发布