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:com.symbian.driver.remoting.master.TestMaster.java

/**
 * Start master./*from   ww  w.  j  av a  2 s  .  c om*/
 */
public void start() {

    String bindingName = null;
    String jobsFolder = null;
    String lHostName = null;
    String lServiceName = null;

    // start rmi registry
    /*
     * The user can specify the ip@ or the host name at config --server
     */
    try {

        TDConfig CONFIG = TDConfig.getInstance();
        lHostName = CONFIG.getPreference(TDConfig.SERVER_NAME);
        lServiceName = CONFIG.getPreference(TDConfig.SERVICE);

        LOGGER.fine("Host: " + lHostName + " RMI Service: " + lServiceName);

        jobsFolder = CONFIG.getPreferenceFile(TDConfig.JOBS_FOLDER).getAbsolutePath();
        if (lHostName.matches("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")) {
            LOGGER.fine("Using host ip address for RMI from the config : " + lHostName);
            lHostName = InetAddress.getByName(lHostName).getHostName();
        }

        if (lHostName == null) {
            LOGGER.log(Level.SEVERE, "Could not determine the Host Name. Please check your config.");
            System.exit(-1);
        }

        System.getProperties().setProperty("java.rmi.server.hostname", lHostName);
        Registry lRegistry = LocateRegistry.createRegistry(1099);
        LOGGER.fine("Master: RMI registry ready. " + lRegistry);

    } catch (ParseException lE) {
        LOGGER.log(Level.SEVERE, "Master: Can not parse configuration.", lE);
        System.exit(-1);
    } catch (UnknownHostException lUHE) {
        LOGGER.log(Level.SEVERE, "Invalid host name " + lHostName, lUHE);
        System.exit(-1);
    } catch (RemoteException lRemoteException) {
        LOGGER.log(Level.SEVERE, "Master: RMI registry failed to start " + lRemoteException.getMessage(),
                lRemoteException);
        System.exit(-1);
    }

    File storeFolder = new File(SERIALIZE_FOLDER);
    if (!(storeFolder.isDirectory())) {
        if (!(storeFolder.mkdirs())) {
            LOGGER.log(Level.SEVERE,
                    "Master: Unable to create the store folder." + "Please ensure that the " + SERIALIZE_FOLDER
                            + " folder exists. It is needed by Master for placing system restore files.");
            System.exit(-1);
        }
    }

    try {
        if (ClientRegister.getInstance().needRestore()) {
            LOGGER.info("Restoring Client register.");
            ClientRegister.getInstance().restoreSnapshot();
        }
        if (JobTracker.getInstance().needRestore()) {
            LOGGER.info("Restoring Job tracker.");
            JobTracker.getInstance().restoreSnapshot();
        }
        JobCounter jobCounter = new JobCounter();
        if (jobCounter.needRestore()) {
            LOGGER.info("Restoring Job counter.");
            jobCounter.restoreSnapshot();
        }
        QueuedExecutor queuedExecutor = new QueuedExecutor();
        if (queuedExecutor.needRestore()) {
            LOGGER.info("Restoring execution queue.");
            queuedExecutor.restoreSnapshot();
        }
        bindingName = "//" + lHostName + "/" + lServiceName;
        MasterRemote master = new MasterRemoteImpl(jobsFolder, jobCounter, queuedExecutor);
        Naming.rebind(bindingName, master);
        LOGGER.info("Remote Service Name : " + bindingName);
    } catch (RemoteException lRE) {
        LOGGER.log(Level.SEVERE, "Master: Problem with contacting the RMI Registry: ", lRE);
        System.exit(-1);
    } catch (IOException lE) {
        LOGGER.log(Level.SEVERE, "Master: Problem with starting up TestMaster: ", lE);
        System.exit(-1);
    }
}

From source file:io.mandrel.requests.dns.CachedNameResolver.java

public InetAddress resolve(String name) throws UnknownHostException {
    return name != null ? addresses.computeIfAbsent(name, key -> {
        try {/*from   w  w  w.  j a  v a  2s.  c o m*/
            return InetAddress.getByName(key);
        } catch (UnknownHostException e) {
            log.debug("", e);
            throw Throwables.propagate(e);
        }
    }) : null;
}

From source file:org.tamacat.httpd.util.IpAddressMatcher.java

static InetAddress parseAddress(String address) {
    try {/*from   w  w  w  .  ja  v  a 2  s  .  c o  m*/
        return InetAddress.getByName(address);
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Failed to parse address" + address, e);
    }
}

From source file:cc.arduino.net.PACSupportMethods.java

public String dnsResolve(String host) throws UnknownHostException {
    return InetAddress.getByName(host).getHostAddress();
}

From source file:com.cloudera.sqoop.util.DirectImportUtils.java

/** @return true if someHost refers to localhost.
 *///w  w w. j  a v  a2s  .c  o  m
public static boolean isLocalhost(String someHost) {
    if (null == someHost) {
        return false;
    }

    try {
        InetAddress localHostAddr = InetAddress.getLocalHost();
        InetAddress someAddr = InetAddress.getByName(someHost);

        return localHostAddr.equals(someAddr);
    } catch (UnknownHostException uhe) {
        return false;
    }
}

From source file:com.alibaba.jstorm.utils.NetWorkUtils.java

public static List<String> host2Ip(List<String> servers) {
    if (servers == null || servers.size() == 0) {
        return new ArrayList<String>();
    }//from w ww.j a va2s  .  c  o  m

    Set<String> ret = new HashSet<String>();
    for (String server : servers) {
        if (StringUtils.isBlank(server)) {
            continue;
        }

        InetAddress ia;
        try {
            ia = InetAddress.getByName(server);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            LOG.info("Fail to get address of ", server);
            continue;
        }
        if (ia.isLoopbackAddress() || ia.isAnyLocalAddress()) {
            ret.add(NetWorkUtils.ip());
        } else {
            ret.add(ia.getHostAddress());
        }
    }

    return JStormUtils.mk_list(ret);
}

From source file:edu.uic.udptransmit.UDPTransmit.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if ("initialize".equals(action)) {
        final String host = args.getString(0);
        final int port = args.getInt(1);
        // Run the UDP transmitter initialization on its own thread (just in case, see sendMessage comment)
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                this.initialize(host, port, callbackContext);
            }/*w  ww .  j ava 2 s.  co m*/

            private void initialize(String host, int port, CallbackContext callbackContext) {
                boolean successResolvingIPAddress = false;
                // create packet
                InetAddress address = null;
                try {
                    // 'host' can be a ddd.ddd.ddd.ddd or named URL, so doesn't always resolve
                    address = InetAddress.getByName(host);
                    successResolvingIPAddress = true;
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // If we were able to resolve the IP address from the host name, we're good to try to initialize
                if (successResolvingIPAddress) {
                    byte[] bytes = new byte[0];
                    datagramPacket = new DatagramPacket(bytes, 0, address, port);
                    // create socket
                    try {
                        datagramSocket = new DatagramSocket();
                        successInitializingTransmitter = true;

                    } catch (SocketException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (successInitializingTransmitter)
                    callbackContext.success(
                            "Success initializing UDP transmitter using datagram socket: " + datagramSocket);
                else
                    callbackContext.error(
                            "Error initializing UDP transmitter using datagram socket: " + datagramSocket);
            }
        });
        return true;
    } else if ("sendMessage".equals(action)) {
        final String message = args.getString(0);
        // Run the UDP transmission on its own thread (it fails on some Android environments if run on the same thread)
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                this.sendMessage(message, callbackContext);
            }

            private void sendMessage(String data, CallbackContext callbackContext) {
                boolean messageSent = false;
                // Only attempt to send a packet if the transmitter initialization was successful
                if (successInitializingTransmitter) {
                    byte[] bytes = data.getBytes();
                    datagramPacket.setData(bytes);
                    try {
                        datagramSocket.send(datagramPacket);
                        messageSent = true;
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (messageSent)
                    callbackContext.success("Success transmitting UDP packet: " + datagramPacket);
                else
                    callbackContext.error("Error transmitting UDP packet: " + datagramPacket);
            }
        });
        return true;
    } else if ("resolveHostName".equals(action)) {
        final String url = args.getString(0);
        // Run the UDP transmission on its own thread (it fails on some Android environments if run on the same thread)
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                this.resolveHostName(url, callbackContext);
            }

            private void resolveHostName(String url, CallbackContext callbackContext) {
                boolean hostNameResolved = false;
                InetAddress address = null;
                try {
                    // 'host' can be a ddd.ddd.ddd.ddd or named URL, so doesn't always resolve
                    address = InetAddress.getByName(url);
                    hostNameResolved = true;
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (hostNameResolved)
                    callbackContext.success(address.getHostAddress());
                else
                    callbackContext.error("Error resolving host name: " + url);
            }
        });
        return true;
    } else if ("resolveHostNameWithUserDefinedCallbackString".equals(action)) {
        final String url = args.getString(0);
        final String userString = args.getString(1);
        // Run the UDP transmission on its own thread (it fails on some Android environments if run on the same thread)
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                this.resolveHostNameWithUserDefinedCallbackString(url, userString, callbackContext);
            }

            private void resolveHostNameWithUserDefinedCallbackString(String url, String userString,
                    CallbackContext callbackContext) {
                boolean hostNameResolved = false;
                InetAddress address = null;
                try {
                    // 'host' can be a ddd.ddd.ddd.ddd or named URL, so doesn't always resolve
                    address = InetAddress.getByName(url);
                    hostNameResolved = true;
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (hostNameResolved)
                    callbackContext.success(address.getHostAddress() + "|" + userString);
                else
                    callbackContext.error("|" + userString);
            }
        });
        return true;
    }
    return false;
}

From source file:com.hellblazer.jackal.configuration.basic.LocalMulticastConfiguration.java

@Bean
public MulticastAddress heartbeatGroup() throws UnknownHostException {
    return new MulticastAddress(InetAddress.getByName("233.1.2.30"), 1966, 0);
}

From source file:fi.tut.fast.MulticastConsumer.java

@Override
protected void doStart() throws Exception {
    super.doStart();

    //       System.out.println(endpoint.getEndpointUri());
    //      System.out.println("Starting Comsumer Endpoint on interface " + endpoint.getInterface().getDisplayName());

    LOG.info(String.format("Starting Comsumer Endpoint on interface %s",
            endpoint.getInterface().getDisplayName()));

    messageQueue = new MessageQueue();
    s = new MulticastSocket(endpoint.getMulticastAddress().getPort());
    s.setReuseAddress(true);//from ww  w .j  ava 2  s  . c  o m
    s.setNetworkInterface(endpoint.getInterface());
    s.joinGroup(InetAddress.getByName(endpoint.getMulticastAddress().getHost()));
    s.setSoTimeout(endpoint.getSocketTimeout());

    dlThread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (!done) {
                try {
                    consume();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                s.leaveGroup(InetAddress.getByName(endpoint.getMulticastAddress().getHost()));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            s.close();

        }

    });
    dlThread.setDaemon(true);
    dlThread.start();

}

From source file:gridool.discovery.file.FileDiscoveryService.java

@Override
public void start() throws GridException {
    GridNode localNode = config.getLocalNode();
    handleJoin(localNode);/*from www .j a v  a 2s . com*/

    String userDir = System.getProperty("user.home");
    File file = new File(userDir, "servers.list");
    if (!file.exists()) {
        throw new GridException("Required file does not exist in: " + file.getAbsolutePath());
    }

    final FileReader fr;
    try {
        fr = new FileReader(file);
    } catch (FileNotFoundException e) {
        throw new GridException(e);
    }
    final BufferedReader br = new BufferedReader(fr, 8192);
    final StringBuilder buf = new StringBuilder(512);
    try {
        buf.append("{ ");
        int found = 0;
        String line;
        while (null != (line = br.readLine())) {
            String name = line.trim();
            String[] server = line.split(":");
            if (server.length == 2) {
                String host = server[0];
                int port = Integer.parseInt(server[1]);
                InetAddress addr = InetAddress.getByName(host);
                GridNode node = new GridNodeInfo(addr, port, false);
                if (found != 0) {
                    buf.append(", ");
                }
                buf.append(name);
                handleJoin(node);
                found++;
            }
        }
        buf.append(" }\ntotal " + found + " nodes are joined to the cluster.");
    } catch (IOException e) {
        throw new GridException(e);
    } finally {
        IOUtils.closeQuietly(br);
    }
    if (LOG.isInfoEnabled()) {
        LOG.info(buf);
    }
}