zoukankan      html  css  js  c++  java
  • Get IP Address in Android 4.0+

    在android2.3以下的系统中,可以使用如下的代码来获取Android系统的本地IP地址:

    [java] 
    private String getLocalIPAddress() throws SocketException{ 
        for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){ 
            NetworkInterface intf = en.nextElement();  www.2cto.com
            for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ 
                InetAddress inetAddress = enumIpAddr.nextElement(); 
                if(!inetAddress.isLoopbackAddress())){ 
                    return inetAddress.getHostAddress().toString(); 
                } 
            } 
        } 
        return "null"; 

    但是,在android4.0以上系统中,上面的代码仅能够返回一个ipv6的地址,如果需要获取ip v4的地址,可以这么更改:
    [java] 
    private String getLocalIPAddress() throws SocketException{ 
        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() && <strong>(inetAddress instanceof Inet4Address)</strong>){ 
                    return inetAddress.getHostAddress().toString(); 
                } 
            } 
        } 
        return "null"; 

    需要import的包有:
    import java.net.InetAddress;
    import java.net.Inet4Address;
    import java.net.InetSocketAddress;
    import java.net.NetworkInterface;

  • 相关阅读:
    开启chrome默认支持ipv6
    IC6151试用发现的问题
    锁存器(latch)、触发器(Flipflop)、寄存器(register)的区别
    文件管理小习惯:在特定位置创建快捷方式
    采用SPI接口的芯片
    阅读笔记:TI Grounding in mixedsignal systems demystified, Part 1
    IC6151使用小技巧,摸索中。。。
    基于RBAC模型的权限管理系统的设计和实现(转载)
    Cron 表达式说明
    组织结构及授权系统关系
  • 原文地址:https://www.cnblogs.com/yangzhang/p/3372257.html
Copyright © 2011-2022 走看看