获取一个url里面的域名部分,并取对应的IP地址

比如:取这个地址“"http://blog.csdn.net/meetings/article/details/78785424"”里的“blog.csdn.net”对应的真实IP

    /**
     * 获取url对应的域名
     *
     * @param url
     * @return
     */
    public String getDomain(String url) {
        String result = "";
        int j = 0, startIndex = 0, endIndex = 0;
        for (int i = 0; i < url.length(); i++) {
            if (url.charAt(i) == '/') {
                j++;
                if (j == 2)
                    startIndex = i;
                else if (j == 3)
                    endIndex = i;
            }

        }
        result = url.substring(startIndex + 1, endIndex);
        return result;
    }
    /**
     * 通过域名获取真实的ip地址 (此方法需要在线程中调用)
     *
     * @param domain
     * @return
     */
    public String getIP(String domain) {
        String ipAddress = "";
        InetAddress iAddress = null;
        try {
            iAddress = InetAddress.getByName(domain);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        if (iAddress == null)
            Log.i("xxx", "iAddress ==null");
        else {
            ipAddress = iAddress.getHostAddress();
        }
        return ipAddress;
    }
调用:
    final String url = "http://blog.csdn.net/meetings/article/details/78785424";

        CoreFuncKt.ioThread(new Runnable() {
            @Override
            public void run() {
                Log.i("ddd", "IP" + getIP(getDomain(url)));
            }
        });
执行结果:47.95.165.112


你可能感兴趣的:(android)