集册 Java实例教程 从名称服务获取所有ip地址;

从名称服务获取所有ip地址;

欢马劈雪     最近更新时间:2020-01-02 10:19:05

428
从名称服务获取所有ip地址;


import java.io.UnsupportedEncodingException;

import java.net.InetAddress;
/**
时代Java
**/

import java.net.UnknownHostException;

import java.util.HashSet;

import java.util.Set;


public class Main{


    public static Set<String> getAllIps(String hostname) {


        Set<String> ips = new HashSet<String>();

        int tryCount = 0;

        while (tryCount++ < 3) {

            try {

                InetAddress[] addresses = InetAddress

                        .getAllByName(hostname);

                for (InetAddress ia : addresses) {
                /* 
                 来自 
                *时   代     Java  公  众  号 - nowjava.com*/

                    ips.add(ia.getHostAddress());

                }

                if (ips.size() > 0) {


                    return ips;

                }

            } catch (UnknownHostException e) {


                safeSleep(nextRandom(100));

            }

        }


        return ips;

    }

    public static void safeSleep(int millis) {

        try {

            Thread.sleep(millis);

        } catch (InterruptedException e) {

            ClientBalancerLog.log.e
展开阅读全文