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.predic8.membrane.core.interceptor.acl.Hostname.java

@Override
public boolean matches(String hostname, String ip) {
    try {//from  w w  w.j  av  a2s  . co m
        if (pattern.toString().equals("^localhost$")) {
            InetAddress ia = InetAddress.getByName(ip);
            if (ia.equals(localhostIp4) || ia.equals(localhostIp6)) {
                log.debug("Address to be matched : " + ia + " is being matched to :" + pattern.toString());
                return true;
            }
        }
        if (!reverseDNS) {
            long now = System.currentTimeMillis();
            if (now - lastWarningSlowReverseDNSUsed > 10 * 60 * 1000) {
                log.warn(
                        "transport/@reverseDNS=false is incompatible with ACL hostname filtering. (Please use ip filtering instead.) Slow reverse DNS lookup will be performed.");
                lastWarningSlowReverseDNSUsed = now;
            }
        }
        String canonicalHostName = router.getDnsCache().getCanonicalHostName(InetAddress.getByName(ip));
        log.debug("CanonicalHostname for " + hostname + " / " + ip + " is " + canonicalHostName);
        return pattern.matcher(canonicalHostName).matches();
    } catch (UnknownHostException e) {
        log.warn("Could not reverse lookup canonical hostname for " + hostname + " " + ip + ".", e);
        return false;
    }
}

From source file:org.janusgraph.diskstorage.es.ElasticSearchIndexTest.java

@BeforeClass
public static void startElasticsearch() throws Exception {
    esr = new ElasticsearchRunner();
    esr.start();/* ww w .jav a2s  .c  o m*/
    httpClient = HttpClients.createDefault();
    objectMapper = new ObjectMapper();
    host = new HttpHost(InetAddress.getByName(esr.getHostname()), ElasticsearchRunner.PORT);
    if (esr.getEsMajorVersion().value > 2) {
        IOUtils.closeQuietly(httpClient.execute(host, new HttpDelete("_ingest/pipeline/pipeline_1")));
        final HttpPut newPipeline = new HttpPut("_ingest/pipeline/pipeline_1");
        newPipeline.setHeader("Content-Type", "application/json");
        newPipeline.setEntity(
                new StringEntity("{\"description\":\"Test pipeline\",\"processors\":[{\"set\":{\"field\":\""
                        + STRING + "\",\"value\":\"hello\"}}]}", Charset.forName("UTF-8")));
        IOUtils.closeQuietly(httpClient.execute(host, newPipeline));
    }
}

From source file:com.neophob.sematrix.core.output.E1_31Device.java

/**
 * //from   w  ww .j  a va  2s . c  o  m
 * @param controller
 */
public E1_31Device(ApplicationConfigurationHelper ph, int nrOfScreens) {
    super(OutputDeviceEnum.E1_31, ph, 8, nrOfScreens);
    this.displayOptions = ph.getE131Device();

    //Get dmx specific config
    this.pixelsPerUniverse = ph.getE131PixelsPerUniverse();

    try {
        String ip = ph.getE131Ip();
        String sendMode = "Unicast";
        if (StringUtils.startsWith(ip, MULTICAST_START)) {
            this.sendMulticast = true;
            sendMode = "Multicast";
        }
        this.targetAdress = InetAddress.getByName(ip);
        this.firstUniverseId = ph.getE131StartUniverseId();
        calculateNrOfUniverse();
        packet = new DatagramPacket(new byte[0], 0, targetAdress, E1_31DataPacket.E131_PORT);
        dsocket = new DatagramSocket();

        this.initialized = true;

        LOG.log(Level.INFO, "E1.31 device initialized, send mode: " + sendMode + ", use "
                + this.displayOptions.size() + " panels");
    } catch (Exception e) {
        LOG.log(Level.WARNING, "failed to initialize E1.31 device", e);
    }
}

From source file:org.thoughtcrime.securesms.mms.MmsCommunication.java

private static void checkRouteToHost(Context context, String host) throws IOException {
    InetAddress inetAddress = InetAddress.getByName(host);
    byte[] ipAddressBytes = inetAddress.getAddress();
    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.");
    //        if (!manager.requestRouteToHost(ConnectivityManager.TYPE_MOBILE, ipAddress))
    //           throw new IOException("Connection manager could not obtain route to host.");      

}

From source file:com.couchbase.client.core.config.DefaultNodeInfo.java

/**
 * Creates a new {@link DefaultNodeInfo} with no SSL services.
 *
 * @param viewUri  the URI of the view service.
 * @param hostname the hostname of the node.
 * @param ports    the port list of the node services.
 *//*w w  w .  j av a2 s. c  om*/
@JsonCreator
public DefaultNodeInfo(@JsonProperty("couchApiBase") String viewUri, @JsonProperty("hostname") String hostname,
        @JsonProperty("ports") Map<String, Integer> ports) {
    if (hostname == null) {
        throw new CouchbaseException(new IllegalArgumentException("NodeInfo hostname cannot be null"));
    }

    try {
        this.hostname = InetAddress.getByName(trimPort(hostname));
    } catch (UnknownHostException e) {
        throw new CouchbaseException("Could not analyze hostname from config.", e);
    }
    this.directServices = parseDirectServices(viewUri, ports);
    this.sslServices = new HashMap<ServiceType, Integer>();
}

From source file:software.uncharted.elasticsearch.ElasticClient.java

@PostConstruct
public ElasticClient init() throws Exception {

    final Settings settings = Settings.settingsBuilder().put("cluster.name", elasticCluster)
            .put("client.transport.sniff", false).build();

    try {//from w ww  . j  av a 2  s .  co  m
        client = TransportClient.builder().settings(settings).build();
        client.addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName(elasticHost), elasticPort));
    } catch (final Exception ex) {
        throw new Exception("Could not connect to Elastic.", ex);
    }
    return this;
}

From source file:edu.cornell.med.icb.ip.IpUtils.java

/**
 * Attempt to validate an IP address or hostname with optional comment.
 * This can be in the formation of "address_or_hostname # comment".
 * Whitespace (space or tab) can padd the valiues anywhere within
 * the value, except within the ip address / hostname iteself. If specifying
 * an ip address must be four values seperated by ".", each value must be 0 - 255...
 * this is not exactly true, see the documentation for java.net.InetAddress
 * for actual parsing rules of ip addresses.
 * @param toValidate the ip address and/or hostname (with optional comment) to try to validate
 * @return an IpAddress object containing the InetAddress and any comment.
 * If the line didn't parse UnknownHostname exception will be thrown. If the line
 * contains ONLY a comment IpAddress.ipAddress will be null but comment will be
 * filled in. If the line is blank (or empty) an IpAddress will be returned
 * with IpAddress.ipAddress as null and an empty String comment.
 * @throws UnknownHostException error parsing the ip address / hostname part of the string
 *///from  w  w  w  .  ja v  a 2  s.c o m
public static IpAddress validateIpAddress(final String toValidate) throws UnknownHostException {
    final String trimmedIpAddress;
    if (StringUtils.isBlank(toValidate)) {
        // No IP, no comment. Blank-ish line
        return new IpAddress(null, "");
    } else {
        trimmedIpAddress = toValidate.trim();
    }

    String comment = "";
    // parse out any comments
    if (trimmedIpAddress.charAt(0) == '#') {
        // Comment only line
        return new IpAddress(null, trimmedIpAddress.substring(1).trim());
    }

    final String[] ipAndCommentParts = StringUtils.split(trimmedIpAddress, "#", 2);
    final String ipNoComment = ipAndCommentParts[0].trim();
    if (ipAndCommentParts.length == 2) {
        // Both IP AND comment
        comment = ipAndCommentParts[1].trim();
    }

    final InetAddress ipAddress = InetAddress.getByName(ipNoComment);
    return new IpAddress(ipAddress, comment);
}

From source file:com.edmunds.etm.common.api.AgentInstance.java

/**
 * Gets the host name.//from  www. j  av a 2s. c  o m
 *
 * @return host name
 */
public String getHostName() {
    if (hostName == null) {
        try {
            InetAddress addr = InetAddress.getByName(ipAddress);
            hostName = addr.getHostName();
        } catch (UnknownHostException e) {
            return "Unknown";
        }
    }
    return hostName;
}

From source file:com.opensoc.enrichment.adapters.geo.GeoMysqlAdapter.java

@SuppressWarnings("unchecked")
@Override//  www  .j  av a  2 s . c o  m
public JSONObject enrich(String metadata) {

    ResultSet resultSet = null;

    try {

        _LOG.trace("[OpenSOC] Received metadata: " + metadata);

        InetAddress addr = InetAddress.getByName(metadata);

        if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress()
                || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) {
            _LOG.trace("[OpenSOC] Not a remote IP: " + metadata);
            _LOG.trace("[OpenSOC] Returning enrichment: " + "{}");

            return new JSONObject();
        }

        _LOG.trace("[OpenSOC] Is a valid remote IP: " + metadata);

        statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS";
        resultSet = statement.executeQuery(locid_query);

        if (resultSet == null)
            throw new Exception(
                    "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query);

        resultSet.last();
        int size = resultSet.getRow();

        if (size == 0)
            throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query);

        resultSet.beforeFirst();
        resultSet.next();

        String locid = null;
        locid = resultSet.getString("ANS");

        if (locid == null)
            throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query);

        String geo_query = "select * from location where locID = " + locid + ";";
        resultSet = statement.executeQuery(geo_query);

        if (resultSet == null)
            throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid
                    + ". Query run was: " + geo_query);

        resultSet.last();
        size = resultSet.getRow();

        if (size == 0)
            throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid
                    + ". Query run was: " + geo_query);

        resultSet.beforeFirst();
        resultSet.next();

        JSONObject jo = new JSONObject();
        jo.put("locID", resultSet.getString("locID"));
        jo.put("country", resultSet.getString("country"));
        jo.put("city", resultSet.getString("city"));
        jo.put("postalCode", resultSet.getString("postalCode"));
        jo.put("latitude", resultSet.getString("latitude"));
        jo.put("longitude", resultSet.getString("longitude"));
        jo.put("dmaCode", resultSet.getString("dmaCode"));
        jo.put("locID", resultSet.getString("locID"));

        jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude"));

        _LOG.debug("Returning enrichment: " + jo);

        return jo;

    } catch (Exception e) {
        e.printStackTrace();
        _LOG.error("Enrichment failure: " + e);
        return new JSONObject();
    }
}

From source file:com.sshtools.j2ssh.agent.SshAgentSocketListener.java

/**
 * Creates a new SshAgentSocketListener object.
 *
 * @param location the location of the listening agent. This should be a
 *        random port on the localhost such as localhost:15342
 * @param keystore the keystore for agent operation
 *
 * @throws AgentNotAvailableException if the location specifies an invalid
 *         location//from w  w  w . j  a v  a2 s  . c  o  m
 */
public SshAgentSocketListener(String location, KeyStore keystore) throws AgentNotAvailableException {
    log.info("New SshAgent instance created");

    // Verify the agent location
    this.location = location;

    if (location == null) {
        throw new AgentNotAvailableException();
    }

    this.location = location;

    int idx = location.indexOf(":");

    if (idx == -1) {
        throw new AgentNotAvailableException();
    }

    String host = location.substring(0, idx);
    port = Integer.parseInt(location.substring(idx + 1));

    this.keystore = keystore;

    try {
        server = new ServerSocket(port, 5, InetAddress.getByName(host));
    } catch (Exception e) {
        e.printStackTrace();
    }
}