zoukankan      html  css  js  c++  java
  • Android 手机上获取手机当前上网IP地址

     

    [转] 原文 

                 Android 手机上获取手机当前上网IP地址
                    (手机网关给手机号分配的IP)


    每个手机上网通过移动网关的时候,网关都会给该手机号分配一个IP地址(当然这个IP地址会在下线上线后会改变,网关都有记录的)

    现在做的应用需要获取该IP地址,提交给服务器,代码如下:

    [java] view plain copy
    1. /** 
    2.  * 用来获取手机拨号上网(包括CTWAP和CTNET)时由PDSN分配给手机终端的源IP地址。 
    3.  *  
    4.  * @return 
    5.  * @author SHANHY 
    6.  */  
    7. public static String getPsdnIp() {  
    8.     try {  
    9.         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {  
    10.             NetworkInterface intf = en.nextElement();  
    11.             for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {  
    12.                 InetAddress inetAddress = enumIpAddr.nextElement();  
    13.                 if (!inetAddress.isLoopbackAddress()) {  
    14.                     return inetAddress.getHostAddress().toString();  
    15.                 }  
    16.             }  
    17.         }  
    18.     } catch (Exception e) {  
    19.     }  
    20.     return "";  
    21. }  

    如上这样写,在有些情况下就会有问题了,比如我现在用的是安卓4.0系统的手机,按上面的方法默认会先获取到ipv6的地址,有时候我们只想要ipv4的地址,就需要再多做个类型判断,代码如下:

    [java] view plain copy
    1. /** 
    2.  * 用来获取手机拨号上网(包括CTWAP和CTNET)时由PDSN分配给手机终端的源IP地址。 
    3.  *  
    4.  * @return 
    5.  * @author SHANHY 
    6.  */  
    7. public static String getPsdnIp() {  
    8.     try {  
    9.         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {  
    10.             NetworkInterface intf = en.nextElement();  
    11.             for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {  
    12.                 InetAddress inetAddress = enumIpAddr.nextElement();  
    13.                 if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {  
    14.                 //if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {  
    15.                     return inetAddress.getHostAddress().toString();  
    16.                 }  
    17.             }  
    18.         }  
    19.     } catch (Exception e) {  
    20.     }  
    21.     return "";  
    22. }  

    ----------------------------------------------------------------------------

    谢谢~~~

  • 相关阅读:
    linux --- 3 vim 网络 用户 权限 软连接 压缩 定时任务 yum源
    linux --- 2.常用命令 , python3, django安装
    linux --- 1.初始linux
    admin ---11.admin , 展示列表 和 分页
    并发 ---- 6. IO 多路复用
    django基础 -- 10.form , ModelForm ,modelformset
    django基础 -- 9.中间件
    flask基础
    MySQL-数据库增删改查
    面试题目二
  • 原文地址:https://www.cnblogs.com/wxmdevelop/p/6632565.html
Copyright © 2011-2022 走看看