Android获取本机IP地址,绝对可行

来源:互联网 发布:公开网络摄像头 编辑:程序博客网 时间:2024/06/06 08:48

之前有个需求,统计新增APP用户,需要获取用户的IP地址,到网上参考了很多例子,如果手机连接的是wifi,获取到是192.168.1.1这种格式的地址,如果连接的是移动网络,获取到的是10.109.51.213这种格式。

    /**     * 获取ip地址     * @return     */    public static String getHostIP() {        String hostIp = null;        try {            Enumeration nis = NetworkInterface.getNetworkInterfaces();            InetAddress ia = null;            while (nis.hasMoreElements()) {                NetworkInterface ni = (NetworkInterface) nis.nextElement();                Enumeration<InetAddress> ias = ni.getInetAddresses();                while (ias.hasMoreElements()) {                    ia = ias.nextElement();                    if (ia instanceof Inet6Address) {                        continue;// skip ipv6                    }                    String ip = ia.getHostAddress();                    if (!"127.0.0.1".equals(ip)) {                        hostIp = ia.getHostAddress();                        break;                    }                }            }        } catch (SocketException e) {            Log.i("yao", "SocketException");            e.printStackTrace();        }        return hostIp;    }


2 3