Gets all the ip address from the name service; - Java Network

Java examples for Network:Host

Description

Gets all the ip address from the name service;

Demo Code


import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
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) {
                    ips.add(ia.getHostAddress());
                }/*ww w. j  a v  a 2s . co m*/
                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.error("Error when thread sleep", e);
        }
    }
    private static int nextRandom(int seed) {
        return (int) (Math.random() * seed);
    }
}

Related Tutorials