德莱華 2015-06-23 04:33 采纳率: 75%
浏览 3178
已采纳

Android通过获取IP的代码获取到的IP不对

下面是获取IP的代码:
public String getLocalIpAddress() {

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()) {

return inetAddress.getHostAddress().toString();

}

}

}

} catch (SocketException ex) {

Log.e("WifiPreference IpAddress", ex.toString());

}

return null;

}

    我在我的小米手机上用这个方法获取本机的IP地址,获取到的IP是10.0.2.15,可是我在设置里找到本机的IP地址是10.88.134.210,这是为什么啊,还有我连上wifi后的ip地址应该是10.225.134.22,但是通过这个方法获取到的IP地址还是10.0.2.15,求大神指点迷津!!!!!!
  • 写回答

3条回答 默认 最新

  • sanbo_xyz 2015-06-23 04:45
    关注

    //必写


    //必写

    // 获取本地IP
    public static String test() {
    try {
    for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = (NetworkInterface) en.nextElement();
    for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
    return inetAddress.getHostAddress().toString();
    }
    }
    }
    } catch (SocketException ex) {
    Log.e("WifiPreference IpAddress", ex.toString());
    }
    return null;
    }

    private void initView() {
        this.findViewById(R.id.btnInsert).setOnClickListener(this);
        this.findViewById(R.id.btnDel).setOnClickListener(this);
        this.findViewById(R.id.btnUpdate).setOnClickListener(this);
        this.findViewById(R.id.btnQuery).setOnClickListener(this);
        if (isBase) {
            mDataManager = DataManager.getInstance(this);
        }
    }
    

    4.2.1手机工作ok

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试