最近看了好多網(wǎng)上獲取IP地址的例子,發(fā)現(xiàn)好多都不完全準(zhǔn)確,這里我寫一下獲取ip地址的兩種方式。 比如微信支付,后臺在做接口的時候,要求App端傳入IP地址,我們需要判斷是網(wǎng)絡(luò)環(huán)境,WI-FI還是3G,所以需要獲取這兩種環(huán)境的ip地址。 第一步:首先是判斷網(wǎng)絡(luò)環(huán)境: String ip; ConnectivityManager conMann = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mobileNetworkInfo.isConnected()) { ip = getLocalIpAddress(); System.out.println('本地ip-----'+ip); }else if(wifiNetworkInfo.isConnected()) { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); ip = intToIp(ipAddress); System.out.println('wifi_ip地址為------'+ip); } 如果連接的是移動網(wǎng)絡(luò),第二步,獲取本地ip地址:getLocalIpAddress();這樣獲取的是ipv4格式的ip地址。 public String getLocalIpAddress() { try { String ipv4; ArrayList nilist = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface ni: nilist) { ArrayList ialist = Collections.list(ni.getInetAddresses()); for (InetAddress address: ialist){ if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress())) { return ipv4; } } } } catch (SocketException ex) { Log.e('localip', ex.toString()); } return null; } 如果連接的是WI-FI網(wǎng)絡(luò),第三步,獲取WI-FI ip地址:intToIp(ipAddress); public static String intToIp(int ipInt) { StringBuilder sb = new StringBuilder(); sb.append(ipInt & 0xFF).append('.'); sb.append((ipInt >> 8) & 0xFF).append('.'); sb.append((ipInt >> 16) & 0xFF).append('.'); sb.append((ipInt >> 24) & 0xFF); return sb.toString(); } 網(wǎng)上的很多代碼獲取的是ipv6的本地ip,在微信支付里這種ip地址無法調(diào)起微信支付,附代碼: private String getlocalIp() { String ip; try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()) { // ip=inetAddress.getHostAddress().toString(); System.out.println('ip=========='+inetAddress.getHostAddress().toString()); return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e('WifiPreference IpAddress', ex.toString()); } return null; } 本文主要介紹了Android準(zhǔn)確獲取手機IP地址的兩種方式,更多關(guān)于Android獲取手機IP地址的方式請查看下面的相關(guān)鏈接 |
|