Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

In this page you can find the example usage for java.net InetAddress getByName.

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:SocketFetcher.java

/**
 * This method returns a Socket. Properties control the use of socket
 * factories and other socket characteristics. The properties used are:
 * <p>/*from  w  w  w  . java2  s  .  c o m*/
 * <ul>
 * <li> <i>prefix</i>.socketFactory.class
 * <li> <i>prefix</i>.socketFactory.fallback
 * <li> <i>prefix</i>.socketFactory.port
 * <li> <i>prefix</i>.timeout
 * <li> <i>prefix</i>.connectiontimeout
 * <li> <i>prefix</i>.localaddress
 * <li> <i>prefix</i>.localport
 * </ul>
 * <p>
 * If the socketFactory.class property isn't set, the socket returned is an
 * instance of java.net.Socket connected to the given host and port. If the
 * socketFactory.class property is set, it is expected to contain a fully
 * qualified classname of a javax.net.SocketFactory subclass. In this case,
 * the class is dynamically instantiated and a socket created by that
 * SocketFactory is returned.
 * <p>
 * 
 * If the socketFactory.fallback property is set to false, don't fall back to
 * using regular sockets if the socket factory fails.
 * <p>
 * 
 * The socketFactory.port specifies a port to use when connecting through the
 * socket factory. If unset, the port argument will be used.
 * <p>
 * 
 * If the connectiontimeout property is set, we use a separate thread to make
 * the connection so that we can timeout that connection attempt.
 * <p>
 * 
 * If the timeout property is set, it is used to set the socket timeout.
 * <p>
 * 
 * If the localaddress property is set, it's used as the local address to bind
 * to. If the localport property is also set, it's used as the local port
 * number to bind to.
 * 
 * @param host
 *          The host to connect to
 * @param port
 *          The port to connect to at the host
 * @param props
 *          Properties object containing socket properties
 * @param prefix
 *          Property name prefix, e.g., "mail.imap"
 * @param useSSL
 *          use the SSL socket factory as the default
 */
public static Socket getSocket(String host, int port, Properties props, String prefix, boolean useSSL)
        throws IOException {

    if (prefix == null)
        prefix = "socket";
    if (props == null)
        props = new Properties(); // empty
    String s = props.getProperty(prefix + ".connectiontimeout", null);
    int cto = -1;
    if (s != null) {
        try {
            cto = Integer.parseInt(s);
        } catch (NumberFormatException nfex) {
        }
    }

    Socket socket = null;
    String timeout = props.getProperty(prefix + ".timeout", null);
    String localaddrstr = props.getProperty(prefix + ".localaddress", null);
    InetAddress localaddr = null;
    if (localaddrstr != null)
        localaddr = InetAddress.getByName(localaddrstr);
    String localportstr = props.getProperty(prefix + ".localport", null);
    int localport = 0;
    if (localportstr != null) {
        try {
            localport = Integer.parseInt(localportstr);
        } catch (NumberFormatException nfex) {
        }
    }

    boolean fb = false;
    String fallback = props.getProperty(prefix + ".socketFactory.fallback", null);
    fb = fallback == null || (!fallback.equalsIgnoreCase("false"));

    String sfClass = props.getProperty(prefix + ".socketFactory.class", null);
    int sfPort = -1;
    try {
        SocketFactory sf = getSocketFactory(sfClass);
        if (sf != null) {
            String sfPortStr = props.getProperty(prefix + ".socketFactory.port", null);
            if (sfPortStr != null) {
                try {
                    sfPort = Integer.parseInt(sfPortStr);
                } catch (NumberFormatException nfex) {
                }
            }

            // if port passed in via property isn't valid, use param
            if (sfPort == -1)
                sfPort = port;
            socket = createSocket(localaddr, localport, host, sfPort, cto, sf, useSSL);
        }
    } catch (Exception ex) {
        if (!fb) {
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t instanceof Exception)
                    ex = (Exception) t;
            }
            if (ex instanceof IOException)
                throw (IOException) ex;
            IOException ioex = new IOException("Couldn't connect using \"" + sfClass
                    + "\" socket factory to host, port: " + host + ", " + sfPort + "; Exception: " + ex);
            throw ioex;
        }
    }

    if (socket == null)
        socket = createSocket(localaddr, localport, host, port, cto, null, useSSL);

    int to = -1;
    if (timeout != null) {
        try {
            to = Integer.parseInt(timeout);
        } catch (NumberFormatException nfex) {
        }
    }
    if (to >= 0)
        socket.setSoTimeout(to);

    configureSSLSocket(socket, props, prefix);
    return socket;
}

From source file:ruiliu2.practice.elasticsearch.client.TransportClientFactoryBean.java

protected void buildClient() throws Exception {
    client = new PreBuiltTransportClient(settings());
    Assert.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing.");
    for (String clusterNode : split(clusterNodes, COMMA)) {
        String hostName = substringBeforeLast(clusterNode, COLON);
        String port = substringAfterLast(clusterNode, COLON);
        Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
        Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
        logger.info("adding transport node : " + clusterNode);
        client.addTransportAddress(/*from w w w. j a va  2  s.c  o m*/
                new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)));
    }
    client.connectedNodes();
}

From source file:psiprobe.controllers.WhoisController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    boolean timeout = false;

    String ipAddress = ServletRequestUtils.getStringParameter(request, "ip", null);

    Whois.Response wh = null;/*from w w  w .jav a 2  s .  c om*/
    try {
        wh = Whois.lookup(getDefaultServer(), getDefaultPort(), ipAddress, getLookupTimeout());
    } catch (IOException e) {
        timeout = true;
        logger.trace("", e);
    }

    List<String> lines = null;
    if (wh != null) {
        lines = new ArrayList<>(50);
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new ByteArrayInputStream(wh.getSummary().getBytes())))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }
    }

    String reverseName = null;
    if (ipAddress != null) {
        try {
            reverseName = InetAddress.getByName(ipAddress).getCanonicalHostName();
        } catch (UnknownHostException e) {
            logger.error("could not run a DNS query on {}", ipAddress);
            logger.trace("", e);
        }
    }
    return new ModelAndView(getViewName(), "result", lines).addObject("timeout", timeout)
            .addObject("whoisServer",
                    wh != null ? wh.getServer() + ":" + wh.getPort() : defaultServer + ":" + defaultPort)
            .addObject("domainName", reverseName);
}

From source file:com.uber.tchannel.ping.PingClient.java

public void run() throws Exception {
    TChannel tchannel = new TChannel.Builder("ping-client").build();
    SubChannel subChannel = tchannel.makeSubChannel("ping-server");
    final ConcurrentHashMap<String, Integer> msgs = new ConcurrentHashMap<String, Integer>();
    final CountDownLatch done = new CountDownLatch(requests);

    for (int i = 0; i < requests; i++) {
        JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
                .setBody(new Ping("{'key': 'ping?'}")).setHeader("some", "header").setTimeout(100 + i).build();
        TFuture<JsonResponse<Pong>> f = subChannel.send(request, InetAddress.getByName(host), port);

        f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
            @Override/*from ww w . j a  va  2  s . c  om*/
            public void onResponse(JsonResponse<Pong> pongResponse) {
                done.countDown();
                String msg = pongResponse.toString();
                if (msgs.containsKey(msg)) {
                    msgs.put(msg, msgs.get(msg) + 1);
                } else {
                    msgs.put(msg, 1);
                }
            }
        });
    }

    done.await();
    for (String msg : msgs.keySet()) {
        System.out.println(String.format("%s\n\tcount:%d", msg, msgs.get(msg)));
    }

    tchannel.shutdown(false);
}

From source file:net.sf.jinsim.UDPChannel.java

/**
 * Construct a Receiver that is ready to communicate with a LFS server at a particular address.
 * /* ww  w  . j  av  a  2s .  com*/
 * @param channel
 *            The DatagramChannel that the communication will take place on.
 * @param address
 *            A network address to send acknowledgement (ACK) packets to.
 * @param multicast
 *            Receiver will relay the packets received to a multicast address if multicast is true.
 * @throws IOException
 */
public UDPChannel(InetSocketAddress address, boolean multicast) throws IOException {
    super();

    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);
    datagramChannel.socket().bind(null);
    //datagramChannel.connect(address);
    this.address = address;

    if (multicast) {
        InetAddress group = InetAddress.getByName("223.223.223.223");
        multicastSocket = new MulticastSocket();
        multicastSocket.joinGroup(group);
    }

}

From source file:com.clustercontrol.ping.util.ReachAddress.java

/**
 * ????????????//from  w ww  .  j a  va  2  s .c om
 * 
 * @param addressText
 * @return PING
 */
private boolean isReachable(String addressText) {

    m_message = null;
    m_messageOrg = null;
    m_lost = 0;
    m_average = 0;

    try {
        long max = 0;
        long min = 0;
        long sum = 0;
        int num = 0;
        long start = 0;
        long end = 0;

        // 
        StringBuffer buffer = new StringBuffer();

        InetAddress address = InetAddress.getByName(addressText);
        buffer.append("Pinging " + address.getHostName() + " [" + address.getHostAddress() + "].\n\n");

        int i = 0;
        for (; i < m_sentCount; i++) {

            // Reachability ?? ICMP ??
            boolean isReachable;
            // isReachable?????????
            synchronized (m_syncObj) {
                start = HinemosTime.currentTimeMillis();
                isReachable = address.isReachable(m_timeout);
                end = HinemosTime.currentTimeMillis();
            }

            long time = end - start;

            if (isReachable) {
                buffer.append("Reply from " + address.getHostAddress() + ": ");

                sum += time;

                if (i == 0) {
                    max = time;
                    min = time;
                } else {
                    if (time > max) {
                        max = time;
                    } else if (time < min) {
                        min = time;
                    }
                }
                num++;

                if (time > 0) {
                    buffer.append("time=" + time + "ms\n");
                } else {
                    buffer.append("time<1ms\n");
                }
            } else {
                if (time >= m_timeout) {
                    buffer.append("Request timed out.\n");
                } else {
                    buffer.append(
                            "Reply from " + address.getHostAddress() + ": Destination net unreachable.\n");
                    //                        num++;
                }
            }

            if (i < m_sentCount - 1) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        buffer.append("\nPing statistics for " + address.getHostAddress() + ":\n");
        //
        if (num == 0) {
            m_lost = 100;
        } else {
            m_lost = (i - num) * 100 / i;
        }

        //
        m_message = "Packets: Sent = " + i + ", Received = " + num + ", Lost = " + (i - num) + " (" + m_lost
                + "% loss),";

        buffer.append("\t" + m_message + "\n");

        buffer.append("Approximate round trip times in milli-seconds:\n");

        // ?
        if (num != 0) {
            m_average = sum / num;
        } else {
            m_average = 0;
        }

        buffer.append("\tMinimum = " + min + "ms, Maximum = " + max + "ms, Average = " + m_average + "ms\n");

        m_messageOrg = buffer.toString();
        return true;

    } catch (UnknownHostException e) {
        m_log.warn("isReachable() " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_PING.getMessage()
                + e.getClass().getSimpleName() + ", " + e.getMessage(), e);

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_PING.getMessage() + " (" + e.getMessage() + ")";
    } catch (IOException e) {
        m_log.warn("isReachable() " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_PING.getMessage()
                + e.getClass().getSimpleName() + ", " + e.getMessage(), e);

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_PING.getMessage() + " (" + e.getMessage() + ")";
    }
    return false;
}

From source file:net.facework.core.streaming.misc.UriParser.java

public static void parse(String uri, Session session) throws IllegalStateException, IOException {
    boolean flash = false;
    int camera = CameraInfo.CAMERA_FACING_FRONT;
    Log.i("UriParser", "RTSP server received:" + uri);
    String[] uriItem = uri.split("/");
    filename = uriItem[uriItem.length - 1];

    List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri), "UTF-8");
    if (params.size() > 0) {

        // Those parameters must be parsed first or else they won't necessarily be taken into account
        for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
            NameValuePair param = it.next();
            // play file
            if (param.getName().equals("file")) {
                Log.i("UriParser", "file name:" + param.getValue());
                session.setFile(param.getValue());
                session.addFileVideoTrack(Session.FILE_VIDEO_H264);
                Log.i("UriParser", "RTSP work in FILE_VIDEO_H264 Mode. FILE:" + param.getValue());
                session.addFileAudioTrack(Session.FILE_AUDIO_AAC);
                Log.i("UriParser", "RTSP work in FILE_AUDIO_AAC Mode. FILE:" + param.getValue());
                session.setFileMode();/*w  w  w . j a v a2s. c om*/

                break;
            }
            // FLASH ON/OFF
            if (param.getName().equals("flash")) {
                if (param.getValue().equals("on"))
                    flash = true;
                else
                    flash = false;
            }

            // CAMERA -> the client can choose between the front facing camera and the back facing camera
            else if (param.getName().equals("camera")) {
                if (param.getValue().equals("back"))
                    camera = CameraInfo.CAMERA_FACING_BACK;
                else if (param.getValue().equals("front"))
                    camera = CameraInfo.CAMERA_FACING_FRONT;
            }

            // MULTICAST -> the stream will be sent to a multicast group
            // The default mutlicast address is 228.5.6.7, but the client can specify one 
            else if (param.getName().equals("multicast")) {
                session.setRoutingScheme(Session.MULTICAST);
                if (param.getValue() != null) {
                    try {
                        InetAddress addr = InetAddress.getByName(param.getValue());
                        if (!addr.isMulticastAddress()) {
                            throw new IllegalStateException("Invalid multicast address !");
                        }
                        session.setDestination(addr);
                    } catch (UnknownHostException e) {
                        throw new IllegalStateException("Invalid multicast address !");
                    }
                } else {
                    // Default multicast address
                    session.setDestination(InetAddress.getByName("228.5.6.7"));
                }
            }

            // UNICAST -> the client can use this so specify where he wants the stream to be sent
            else if (param.getName().equals("unicast")) {
                if (param.getValue() != null) {
                    try {
                        InetAddress addr = InetAddress.getByName(param.getValue());
                        session.setDestination(addr);
                    } catch (UnknownHostException e) {
                        throw new IllegalStateException("Invalid destination address !");
                    }
                }
            }

            // TTL -> the client can modify the time to live of packets
            // By default ttl=64
            else if (param.getName().equals("ttl")) {
                if (param.getValue() != null) {
                    try {
                        int ttl = Integer.parseInt(param.getValue());
                        if (ttl < 0)
                            throw new IllegalStateException("The TTL must be a positive integer !");
                        session.setTimeToLive(ttl);
                    } catch (Exception e) {
                        throw new IllegalStateException("The TTL must be a positive integer !");
                    }
                }
            }

            // No tracks will be added to the session
            else if (param.getName().equals("stop")) {
                return;
            }

        }

        for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
            NameValuePair param = it.next();

            // H264
            if (param.getName().equals("h264")) {
                VideoQuality quality = VideoQuality.parseQuality(param.getValue());
                session.addVideoTrack(Session.VIDEO_H264, camera, quality, flash);
            }

            // H263
            else if (param.getName().equals("h263")) {
                VideoQuality quality = VideoQuality.parseQuality(param.getValue());
                session.addVideoTrack(Session.VIDEO_H263, camera, quality, flash);
            }

            // AMRNB
            else if (param.getName().equals("amrnb") || param.getName().equals("amr")) {
                session.addAudioTrack(Session.AUDIO_AMRNB);
            }

            // AAC
            else if (param.getName().equals("aac")) {
                session.addAudioTrack(Session.AUDIO_AAC);
            }

            // Generic Audio Stream -> make use of api level 12
            // TODO: Doesn't work :/
            else if (param.getName().equals("testnewapi")) {
                session.addAudioTrack(Session.AUDIO_ANDROID_AMR);
            }

        }

        // The default behavior is to only add one video track
        if (session.getTrackCount() == 0) {
            session.addVideoTrack();
            session.addAudioTrack();
        }

    } else if (!filename.contains(":")) {
        if (filename.equals("h264.sdp")) {
            VideoQuality quality = VideoQuality.defaultVideoQualiy.clone();
            session.addVideoTrack(Session.VIDEO_H264, camera, quality, flash);
        } else {
            Log.i("UriParser", "file name:" + filename + ";");
            session.setFile(filename);
            session.addFileVideoTrack(Session.FILE_VIDEO_H264);
            Log.i("UriParser", "RTSP work in FILE_VIDEO_H264 Mode. FILE:" + filename);
            /*session.addFileAudioTrack(Session.FILE_AUDIO_AAC);
            Log.i("UriParser","RTSP work in FILE_AUDIO_AAC Mode. FILE:"+filename);*/
            session.setFileMode();
        }

    }
    // Uri has no parameters: the default behavior is to only add one video track
    else {
        session.addVideoTrack();
        session.addAudioTrack();
    }
}

From source file:org.nuxeo.connect.connector.http.proxy.NashornProxyPacResolver.java

public static String dnsResolve(String host) {
    try {/*from w ww.j  a v a2 s.  co m*/
        return InetAddress.getByName(host).getHostAddress();
    } catch (UnknownHostException e) {
        return "";
    }
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

@Deployment
public static WebArchive deployment() {
    // FIXME hack to get things prepared before the deployment happens
    try {//from  w ww . j  av a  2s.com
        final ModelControllerClient client = ModelControllerClient.Factory
                .create(InetAddress.getByName("localhost"), 9999);
        // create the test connector
        createTestConnector(client);
        // create required security domains
        createSecurityDomains(client);
    } catch (Exception e) {
        // ignore
    }

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    URL webxml = tccl.getResource("web-secure-client-cert.war/web.xml");
    WebArchive war = create("web-secure-client-cert.war", SecuredServlet.class, webxml);
    WebSecurityPasswordBasedBase.printWar(war);
    return war;
}

From source file:com.spotify.cassandra.opstools.autobalance.Main.java

private void run(CommandLine cmd) throws IOException, InterruptedException {
    boolean dryrun = cmd.hasOption("d");
    boolean force = cmd.hasOption("f");
    boolean noresolve = cmd.hasOption("r");
    int port = cmd.hasOption("p") ? Integer.parseInt(cmd.getOptionValue("p")) : 7199;
    String nodehost = cmd.hasOption("h") ? cmd.getOptionValue("h") : "localhost";

    System.out.println("Collecting information about the cluster...");

    NodeProbe nodeProbe = new NodeProbe(nodehost, port);

    if (nodeProbe.getTokens().size() != 1) {
        System.err.println("Cluster is using vnodes and should already be automatically balanced!");
        System.exit(1);/*from   w w  w.ja va 2 s. c o m*/
    }

    boolean hasData = false;
    if (!dryrun) {
        Map<String, String> loadMap = nodeProbe.getLoadMap();
        for (String s : loadMap.values()) {
            if (s.contains("KB"))
                continue;
            if (s.contains("MB") || s.contains("GB") || s.contains("TB")) {
                hasData = true;
                continue;
            }
            throw new RuntimeException("Unknown suffix in load map; don't dare to continue");
        }
    }

    String partitioner = nodeProbe.getPartitioner();
    BigInteger minToken, maxToken;

    if (partitioner.equals(RandomPartitioner.class.getName())) {
        minToken = RandomPartitioner.ZERO;
        maxToken = RandomPartitioner.MAXIMUM;
    } else if (partitioner.equals(Murmur3Partitioner.class.getName())) {
        minToken = BigInteger.valueOf(Murmur3Partitioner.MINIMUM.token);
        maxToken = BigInteger.valueOf(Murmur3Partitioner.MAXIMUM);
    } else {
        throw new RuntimeException("Unsupported partitioner: " + partitioner);
    }

    // Get current mapping of all live nodes

    List<String> liveNodes = nodeProbe.getLiveNodes();

    Map<String, BigInteger> hostTokenMap = new HashMap<String, BigInteger>();
    Map<String, String> hostDcMap = new HashMap<String, String>();

    for (String host : liveNodes) {
        String dc = nodeProbe.getEndpointSnitchInfoProxy().getDatacenter(host);

        String decoratedHost = host;

        if (!noresolve) {
            // Prefix host with canonical host name.
            // This makes things prettier and also causes tokens to be assigned in logical order.
            decoratedHost = InetAddress.getByName(host).getCanonicalHostName() + "/" + host;
        } else {
            decoratedHost = "/" + host;
        }

        hostDcMap.put(decoratedHost, dc);

        List<String> tokens = nodeProbe.getTokens(host);

        if (tokens.size() > 1) {
            throw new RuntimeException("vnodes not supported");
        }
        if (tokens.size() == 0) {
            throw new RuntimeException("No token for " + host + "; aborting");
        }

        hostTokenMap.put(decoratedHost, new BigInteger(tokens.get(0)));
    }

    Balancer balancer = new Balancer(hostTokenMap, hostDcMap, minToken, maxToken);
    Map<String, BigInteger> newMap = balancer.balance();

    List<Operation> operations = new ArrayList<Operation>();

    boolean movesNeeded = false;
    for (Map.Entry<String, BigInteger> entry : hostTokenMap.entrySet()) {
        String host = entry.getKey();
        BigInteger oldToken = entry.getValue();
        BigInteger newToken = newMap.get(host);
        if (!oldToken.equals(newToken)) {
            movesNeeded = true;
        }
        operations.add(new Operation(host, hostDcMap.get(host), oldToken, newToken));
    }

    if (movesNeeded && hasData && !dryrun && !force) {
        dryrun = true;
        System.out.println(
                "The cluster is unbalanced but has data, so no operations will actually be carried out. Use --force if you want the cluster to balance anyway.");
    }

    Collections.sort(operations);

    boolean unbalanced = false, moved = false;
    for (Operation op : operations) {
        if (op.oldToken.equals(op.newToken)) {
            System.out.println(op.host + ": Stays on token " + op.oldToken);
        } else {
            System.out.println(op.host + ": Moving from token " + op.oldToken + " to token " + op.newToken);
            if (!dryrun) {
                String ip = op.host.substring(op.host.lastIndexOf("/") + 1);
                NodeProbe np = new NodeProbe(ip, 7199);
                np.move(op.newToken.toString());
                moved = true;
            } else {
                unbalanced = true;
            }
        }
    }

    if (!unbalanced && moved) {
        System.out.println("The cluster is now balanced!");
    }
}