分享

Android获取IP地址的两种方式(准确版)

 好汉勃士 2022-08-10 发布于广东

最近看了好多网上获取IP地址的例子,发现好多都不完全准确,这里我写一下获取ip地址的两种方式。

比如微信支付,后台在做接口的时候,要求App端传入IP地址,我们需要判断是网络环境,WI-FI还是3G,所以需要获取这两种环境的ip地址。

第一步:首先是判断网络环境:

  1. String ip;
  2. ConnectivityManager conMann = (ConnectivityManager)
  3. this.getSystemService(Context.CONNECTIVITY_SERVICE);
  4. NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
  5. NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  6. if (mobileNetworkInfo.isConnected()) {
  7. ip = getLocalIpAddress();
  8. System.out.println('本地ip-----'+ip);
  9. }else if(wifiNetworkInfo.isConnected())
  10. {
  11. WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  12. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  13. int ipAddress = wifiInfo.getIpAddress();
  14. ip = intToIp(ipAddress);
  15. System.out.println('wifi_ip地址为------'+ip);
  16. }
如果连接的是移动网络,第二步,获取本地ip地址:getLocalIpAddress();这样获取的是ipv4格式的ip地址。
  1. public String getLocalIpAddress() {
  2. try {
  3. String ipv4;
  4. ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
  5. for (NetworkInterface ni: nilist)
  6. {
  7. ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
  8. for (InetAddress address: ialist){
  9. if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress()))
  10. {
  11. return ipv4;
  12. }
  13. }
  14. }
  15. } catch (SocketException ex) {
  16. Log.e('localip', ex.toString());
  17. }
  18. return null;
  19. }
如果连接的是WI-FI网络,第三步,获取WI-FI ip地址:intToIp(ipAddress);
  1. public static String intToIp(int ipInt) {
  2. StringBuilder sb = new StringBuilder();
  3. sb.append(ipInt & 0xFF).append('.');
  4. sb.append((ipInt >> 8) & 0xFF).append('.');
  5. sb.append((ipInt >> 16) & 0xFF).append('.');
  6. sb.append((ipInt >> 24) & 0xFF);
  7. return sb.toString();
  8. }
网上的很多代码获取的是ipv6的本地ip,在微信支付里这种ip地址无法调起微信支付,附代码:
  1. private String getlocalIp() {
  2. String ip;
  3. try {
  4. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
  5. NetworkInterface intf = en.nextElement();
  6. for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
  7. InetAddress inetAddress = enumIpAddr.nextElement();
  8. if (!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()) {
  9. // ip=inetAddress.getHostAddress().toString();
  10. System.out.println('ip=========='+inetAddress.getHostAddress().toString());
  11. return inetAddress.getHostAddress().toString();
  12. }
  13. }
  14. }
  15. } catch (SocketException ex) {
  16. Log.e('WifiPreference IpAddress', ex.toString());
  17. }
  18. return null;
  19. }






    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多