Android开发准确获取手机IP地址的两种方式
最近看了好多网上获取IP地址的例子,发现好多都不完全准确,这里我写一下获取ip地址的两种方式。
比如微信支付,后台在做接口的时候,要求App端传入IP地址,我们需要判断是网络环境,WI-FI还是3G,所以需要获取这两种环境的ip地址。
第一步:首先是判断网络环境:
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); }
如果连接的是移动网络,第二步,获取本地ip地址:getLocalIpAddress();这样获取的是ipv4格式的ip地址。
public String getLocalIpAddress() { try { String ipv4; ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface ni: nilist) { ArrayList<InetAddress> 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网络,第三步,获取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(); }
网上的很多代码获取的是ipv6的本地ip,在微信支付里这种ip地址无法调起微信支付,附代码:
private String getlocalIp() { String ip; 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.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准确获取手机IP地址的两种方式,更多关于Android获取手机IP地址的方式请查看下面的相关链接
赞 (0)