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:edu.tcu.gaduo.ihe.iti.ct_transaction.service.NTPClient.java

public void getRefAddr() {
    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;/*from  w  ww  . j  a  va2 s.  c  om*/
    if (refId != 0) {
        int version = message.getVersion();
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local
            // Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own
            // reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g.
            // 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software
            // distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr))
                        refName = name;
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but
                    // fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV,
            // LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1)
        refAddr += " (" + refName + ")";
    logger.info(" Reference Identifier:\t" + refAddr);
}

From source file:org.fdroid.enigtext.mms.MmsCommunication.java

private static void checkRouteToHost(Context context, String host, boolean usingMmsRadio) throws IOException {
    InetAddress inetAddress = InetAddress.getByName(host);

    if (!usingMmsRadio) {
        if (inetAddress.isSiteLocalAddress()) {
            throw new IOException("RFC1918 address in non-MMS radio situation!");
        }/*from   ww  w  . j a  v  a2s . com*/

        return;
    }

    Log.w("MmsCommunication", "Checking route to address: " + host + " , " + inetAddress.getHostAddress());

    byte[] ipAddressBytes = inetAddress.getAddress();

    if (ipAddressBytes != null && ipAddressBytes.length == 4) {
        int ipAddress = Conversions.byteArrayToIntLittleEndian(ipAddressBytes, 0);
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (!manager.requestRouteToHost(MmsDownloader.TYPE_MOBILE_MMS, ipAddress))
            throw new IOException("Connection manager could not obtain route to host.");
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static String resolveToIp(final String host) {
    try {//from ww  w. j av a  2 s  .c o  m
        final InetAddress addr = InetAddress.getByName(host);
        return ipFromInetAddress(addr);
    } catch (final UnknownHostException e) {
        s_logger.warn("Unable to resolve " + host + " to IP due to UnknownHostException");
        return null;
    }
}

From source file:com.iiitd.networking.UDPMessenger.java

/**
 * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
 * @param message the message to send (multicast). It can't be null or 0-characters long.
 * @return//from  w ww  .  j  av  a  2 s. com
 * @throws IllegalArgumentException
 */
public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0)
        throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
        Log.d(DEBUG_TAG,
                "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
        return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
            e.printStackTrace();
            return false;
        }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    WifiInfo wifiInfo = wim.getConnectionInfo();
    int ipa = wifiInfo.getIpAddress();
    String ipAddress = Formatter.formatIpAddress(ipa);

    try {
        //         packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
        packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipAddress), MULTICAST_PORT);
    } catch (UnknownHostException e) {
        Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
        e.printStackTrace();
        return false;
    }

    try {
        socket.send(packet);
    } catch (IOException e) {
        Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.eviware.soapui.impl.wsdl.support.http.ProxyUtils.java

private static String nslookup(String s, boolean ip) {

    InetAddress host;//from   w  ww  . j  a  va 2 s .  co  m
    String address;

    // get the bytes of the IP address
    try {
        host = InetAddress.getByName(s);
        if (ip)
            address = host.getHostAddress();
        else
            address = host.getHostName();
    } catch (UnknownHostException ue) {
        return s; // no host
    }

    return address;

}

From source file:com.erudika.para.search.ElasticSearchUtils.java

/**
 * Creates an instance of the client that talks to Elasticsearch.
 * @return a client instance//from w  ww  .jav a2 s  . c  o  m
 */
public static Client getClient() {
    if (searchClient != null) {
        return searchClient;
    }
    boolean localNode = Config.getConfigBoolean("es.local_node", true);
    boolean dataNode = Config.getConfigBoolean("es.data_node", true);
    boolean corsEnabled = Config.getConfigBoolean("es.cors_enabled", !Config.IN_PRODUCTION);
    String corsAllowOrigin = Config.getConfigParam("es.cors_allow_origin",
            "/https?:\\/\\/localhost(:[0-9]+)?/");
    String esHome = Config.getConfigParam("es.dir", Paths.get(".").toAbsolutePath().normalize().toString());
    String esHost = Config.getConfigParam("es.transportclient_host", "localhost");
    int esPort = Config.getConfigInt("es.transportclient_port", 9300);
    boolean useTransportClient = Config.getConfigBoolean("es.use_transportclient", false);

    Settings.Builder settings = Settings.builder();
    settings.put("node.name", getNodeName());
    settings.put("client.transport.sniff", true);
    settings.put("action.disable_delete_all_indices", true);
    settings.put("cluster.name", Config.CLUSTER_NAME);
    settings.put("http.cors.enabled", corsEnabled);
    settings.put("http.cors.allow-origin", corsAllowOrigin);
    settings.put("path.home", esHome);
    settings.put("path.data", esHome + File.separator + "data");
    settings.put("path.work", esHome + File.separator + "work");
    settings.put("path.logs", esHome + File.separator + "logs");

    if (Config.IN_PRODUCTION) {
        String discoveryType = Config.getConfigParam("es.discovery_type", "ec2");
        settings.put("cloud.aws.access_key", Config.AWS_ACCESSKEY);
        settings.put("cloud.aws.secret_key", Config.AWS_SECRETKEY);
        settings.put("cloud.aws.region", Config.AWS_REGION);
        settings.put("network.tcp.keep_alive", true);
        settings.put("discovery.type", discoveryType);
        settings.put("discovery.ec2.ping_timeout", "10s");
        if ("ec2".equals(discoveryType)) {
            settings.put("discovery.ec2.groups", Config.getConfigParam("es.discovery_group", "elasticsearch"));
        }
    }

    if (useTransportClient) {
        searchClient = TransportClient.builder().settings(settings).build();
        InetSocketTransportAddress addr;
        try {
            addr = new InetSocketTransportAddress(InetAddress.getByName(esHost), esPort);
        } catch (UnknownHostException ex) {
            addr = new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), esPort);
            logger.warn("Unknown host: " + esHost, ex);
        }
        ((TransportClient) searchClient).addTransportAddress(addr);
    } else {
        searchNode = NodeBuilder.nodeBuilder().settings(settings).local(localNode).data(dataNode).node()
                .start();
        searchClient = searchNode.client();
    }

    Para.addDestroyListener(new Para.DestroyListener() {
        public void onDestroy() {
            shutdownClient();
        }
    });

    if (!existsIndex(Config.APP_NAME_NS)) {
        createIndex(Config.APP_NAME_NS);
    }

    // wait for the shards to initialize - prevents NoShardAvailableActionException!
    String timeout = Config.IN_PRODUCTION ? "1m" : "5s";
    searchClient.admin().cluster().prepareHealth(Config.APP_NAME_NS).setWaitForGreenStatus().setTimeout(timeout)
            .execute().actionGet();

    return searchClient;
}

From source file:com.mendhak.gpslogger.common.OpenGTSClient.java

public void sendRAW(String id, String accountName, SerializableLocation[] locations) throws Exception {
    for (SerializableLocation loc : locations) {
        if (Utilities.IsNullOrEmpty(accountName)) {
            accountName = id;//from w ww .  j  a v a  2  s  .  co m
        }
        String message = accountName + "/" + id + "/" + GPRMCEncode(loc);
        DatagramSocket socket = new DatagramSocket();
        byte[] buffer = message.getBytes();
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(server), port);
        tracer.debug("Sending UDP " + message);
        socket.send(packet);
        socket.close();
    }
}

From source file:com.hs.mail.container.server.DefaultServer.java

public void configure() throws Exception {
    if (!StringUtils.isEmpty(bind) && !"*".equals(bind)) {
        bindTo = InetAddress.getByName(bind);
    }//  w w w .  j  ava  2 s .c  om
}

From source file:org.jboss.as.test.integration.security.loginmodules.usersroles.UsersRolesLoginModuleTestCase8.java

protected static void createSecurityDomains() throws Exception {

    final ModelControllerClient client = ModelControllerClient.Factory
            .create(InetAddress.getByName("localhost"), 9999);
    List<ModelNode> updates = new ArrayList<ModelNode>();

    ModelNode op1 = new ModelNode();

    op1.get(OP).set(ADD);//from  ww w. j  a  v a2 s .co  m
    op1.get(OP_ADDR).add(SUBSYSTEM, "security");
    op1.get(OP_ADDR).add(SECURITY_DOMAIN, "prepare-login-module");
    updates.add(op1);

    op1 = new ModelNode();
    op1.get(OP).set(ADD);
    op1.get(OP_ADDR).add(SUBSYSTEM, "security");
    op1.get(OP_ADDR).add(SECURITY_DOMAIN, "prepare-login-module");
    op1.get(OP_ADDR).add(Constants.AUTHENTICATION, Constants.CLASSIC);

    ModelNode loginModule = op1.get(Constants.LOGIN_MODULES).add();
    loginModule.get(ModelDescriptionConstants.CODE).set(UsersRolesLoginModule.class.getName());
    loginModule.get(FLAG).set("optional");
    op1.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);

    updates.add(op1);

    String securityDomain = "users-roles-login-module";
    ModelNode op2 = new ModelNode();
    op2.get(OP).set(ADD);
    op2.get(OP_ADDR).add(SUBSYSTEM, "security");
    op2.get(OP_ADDR).add(SECURITY_DOMAIN, securityDomain);
    updates.add(op2);

    op2 = new ModelNode();
    op2.get(OP).set(ADD);
    op2.get(OP_ADDR).add(SUBSYSTEM, "security");
    op2.get(OP_ADDR).add(SECURITY_DOMAIN, securityDomain);
    op2.get(OP_ADDR).add(Constants.AUTHENTICATION, Constants.CLASSIC);

    loginModule = op2.get(Constants.LOGIN_MODULES).add();
    loginModule.get(ModelDescriptionConstants.CODE).set(UsersRolesLoginModule.class.getName());
    loginModule.get(FLAG).set("required");
    op2.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);

    URL usersProp = Utils.getResource("users-roles-login-module.war/users.properties");
    URL rolesProp = Utils.getResource("users-roles-login-module.war/roles.properties");
    ModelNode moduleOptions = loginModule.get("module-options");

    Map<String, String> moduleOptionsMap = classModuleOptionsMap.get(UsersRolesLoginModuleTestCase8.class);

    moduleOptions.get("usersProperties").set(usersProp.getFile());
    moduleOptions.get("rolesProperties").set(rolesProp.getFile());
    for (Map.Entry<String, String> entry : moduleOptionsMap.entrySet()) {
        moduleOptions.get(entry.getKey()).set(entry.getValue());
    }

    updates.add(op2);

    applyUpdates(updates, client);

}