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.zotoh.maedr.device.HttpIOTrait.java

/**
 * @return//  w  ww  .  ja va 2s  .  c o  m
 * @throws UnknownHostException
 */
public InetAddress getIP() throws UnknownHostException {
    return isEmpty(_host) ? InetAddress.getLocalHost() : InetAddress.getByName(_host);
}

From source file:com.none.tom.simplerssreader.net.FeedDownloader.java

@SuppressWarnings("ConstantConditions")
public static InputStream getInputStream(final Context context, final String feedUrl) {
    final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class);
    final NetworkInfo info = manager.getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK);
        LogUtils.logError("No network connection");
        return null;
    }/*  w  w  w.  j  a va 2s . c om*/

    URL url;
    try {
        url = new URL(feedUrl);
    } catch (final MalformedURLException e) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e);
        return null;
    }

    final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context);
    final boolean useHttpTorProxy = networkPrefs[0];
    final boolean httpsOnly = networkPrefs[1];
    final boolean followRedir = networkPrefs[2];

    for (int nrRedirects = 0;; nrRedirects++) {
        if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) {
            ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS);
            LogUtils.logError("Too many redirects");
            return null;
        }

        HttpURLConnection conn = null;

        try {
            if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY);
                LogUtils.logError("Attempting insecure connection");
                return null;
            }

            if (useHttpTorProxy) {
                conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT)));
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }

            conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name());

            conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT);
            conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT);

            conn.connect();

            final int responseCode = conn.getResponseCode();

            switch (responseCode) {
            case HttpURLConnection.HTTP_OK:
                return getInputStream(conn.getInputStream());
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case HTTP_TEMP_REDIRECT:
                if (followRedir) {
                    final String location = conn.getHeaderField("Location");
                    url = new URL(url, location);

                    if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                        SharedPrefUtils.updateSubscriptionUrl(context, url.toString());
                    }
                    continue;
                }
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED);
                LogUtils.logError("Couldn't follow redirect");
                return null;
            default:
                if (responseCode < 0) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE);
                    LogUtils.logError("No valid HTTP response");
                    return null;
                } else if (responseCode >= 400 && responseCode <= 500) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT);
                } else if (responseCode >= 500 && responseCode <= 600) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER);
                } else {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED);
                }
                LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage());
                return null;
            }
        } catch (final IOException e) {
            if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable"))
                    || e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e);
            } else {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e);
            }
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}

From source file:com.l2jfree.network.mmocore.MMOController.java

/**
 * Opens a server socket, to accept incoming connections.
 * /*from  w w w  .ja v a 2  s .  co  m*/
 * @param address the address to listen on
 * @param port the port to listen on
 * @throws IOException if any problem occurs while opening the acceptor
 * @throws UnknownHostException if an invalid address was given
 */
public final void openServerSocket(String address, int port) throws IOException, UnknownHostException {
    openServerSocket(InetAddress.getByName(address), port);
}

From source file:fr.jetoile.hadoopunit.component.ElasticSearchBootstrapTest.java

@Test
public void elasticSearchShouldStartWithRealDriver() throws NotFoundServiceException, IOException {

    Settings settings = Settings.builder()
            .put("cluster.name", configuration.getString(HadoopUnitConfig.ELASTICSEARCH_CLUSTER_NAME)).build();
    Client client = TransportClient.builder().settings(settings).build()
            .addTransportAddress(new InetSocketTransportAddress(
                    InetAddress.getByName(configuration.getString(HadoopUnitConfig.ELASTICSEARCH_IP_KEY)),
                    configuration.getInt(HadoopUnitConfig.ELASTICSEARCH_TCP_PORT_KEY)));

    ObjectMapper mapper = new ObjectMapper();

    Sample sample = new Sample("value2", 0.33, 3);

    String jsonString = mapper.writeValueAsString(sample);

    // indexing document
    IndexResponse ir = client.prepareIndex("test_index", "type").setSource(jsonString).setId("2").execute()
            .actionGet();// w w  w . java 2 s  . co m
    client.admin().indices().prepareRefresh("test_index").execute().actionGet();

    assertNotNull(ir);

    GetResponse gr = client.prepareGet("test_index", "type", "2").execute().actionGet();

    assertNotNull(gr);
    assertEquals(gr.getSourceAsString(), "{\"value\":\"value2\",\"size\":0.33,\"price\":3.0}");

}

From source file:com.stratio.cassandra.index.schema.ColumnMapperInet.java

/** {@inheritDoc} */
@Override// www  .  j  a  v a 2 s. c o m
public String queryValue(String name, Object value) {
    if (value == null) {
        return null;
    } else if (value instanceof InetAddress) {
        InetAddress inetAddress = (InetAddress) value;
        return inetAddress.getHostAddress();
    } else if (value instanceof String) {
        String svalue = (String) value;
        if (IPV4_PATTERN.matcher(svalue).matches() || IPV6_PATTERN.matcher(svalue).matches()
                || IPV6_COMPRESSED_PATTERN.matcher(svalue).matches()) {
            try {
                return InetAddress.getByName(svalue).getHostAddress();
            } catch (UnknownHostException e) {
                Log.error(e, e.getMessage());
            }
        } else {
            return svalue;
        }
    }
    throw new IllegalArgumentException(String.format("Value '%s' cannot be cast to InetAddress", value));
}

From source file:experts.net.ip6.ULUA.java

/**
 * Obtain NTP time stamp value/*from w  w w.j  a  v  a2  s .c  om*/
 *
 * @param address
 *            NTP server address
 * @return the current time of day in 64-bit NTP format
 * @throws SocketException
 *             If the socket could not be opened which it might be not available any ports.
 * @throws UnknownHostException
 *             If the host could not be found.
 * @throws IOException
 */
public static long obtainNTPTime(String address) throws SocketException, UnknownHostException, IOException {
    NTPUDPClient client = new NTPUDPClient();
    client.setVersion(NtpV3Packet.VERSION_4);

    // throws SocketException
    client.open();
    // throws UnknownHostException from InetAddress.getByName and IOException from client.getTime
    TimeInfo time = client.getTime(InetAddress.getByName(address));
    client.close();

    time.computeDetails();

    return time.getMessage().getTransmitTimeStamp().ntpValue();
}

From source file:com.abiquo.nodecollector.domain.collectors.AbstractCollector.java

/**
 * Check if two repositories point to the same mount point. It is a helper method that all the
 * Hypervisors can use. It is more complicated than an equals function because one parameter can
 * be informed with the host name of the NFS and the other one with the IP address of the same
 * machine. It also checks if the actualRepository param is accessible.
 * //from  www  .  j ava2s .  co m
 * @param definedRepository NFS string mount point we look for to determine if the host is
 *            Managed.
 * @param actualRepository found NFS repository mounted in the machine.
 * @return true if all the values are actually the same.
 */
protected Boolean checkNFS(String definedRepository, String actualRepository) {

    if (StringUtils.isEmpty(definedRepository)) {
        return false;
    }

    definedRepository = removeTrailingSlash(definedRepository);
    actualRepository = removeTrailingSlash(actualRepository);

    // The value 'host' of the repository NFS, defined by host:path can be actually
    // an IP address or a Host name
    // And the same for the mounted NFS, can be an IP address or a host name.
    // In order to compare if the defined NFS is the mounted NFS, we always will use
    // the IP address. So, maybe we have
    // to convert the host name to and IP address.
    // Get the IP address of the defined NFS.
    String definedHostOrIp = definedRepository.substring(0, definedRepository.indexOf(":"));
    String definedPath = definedRepository.substring(definedRepository.indexOf(":") + 1);
    String definedNFSIPAddress;

    // convert it to String InetAddress IP
    try {
        definedNFSIPAddress = InetAddress.getByName(definedHostOrIp).getHostAddress();
    } catch (UnknownHostException e) {
        return Boolean.FALSE;
    }

    String actualHostOrIp = actualRepository.substring(0, actualRepository.indexOf(":"));
    String actualPath = actualRepository.substring(actualRepository.indexOf(":") + 1);
    String actualNFSIPAddress;
    try {
        actualNFSIPAddress = InetAddress.getByName(actualHostOrIp).getHostAddress();
    } catch (UnknownHostException e) {
        return false;
    }

    if (definedNFSIPAddress.equalsIgnoreCase(actualNFSIPAddress) && definedPath.equalsIgnoreCase(actualPath)) {
        return Boolean.TRUE;
    } else {
        return Boolean.FALSE;
    }
}

From source file:ntpgraphic.PieChart.java

public static void NTPClient(String[] servers) {

    Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema
    defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses
    if (servers.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);/*w  w w.ja v a  2s. c om*/
    }

    Promedio = 0;
    Cant = 0;
    int j = 1;
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : servers) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info, j++);
            } catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
        }
    } catch (SocketException e) {
        System.err.println(e.toString());
    }

    client.close();
    //System.out.println("\n Pomedio "+(Promedio/Cant));
}

From source file:lumbermill.internal.geospatial.GeoIP.java

private Optional<CityResponse> locationOf(String ip) {
    try {//from w w  w  .j a  v  a  2s  .c o  m
        InetAddress ipAddress = InetAddress.getByName(ip);
        CityResponse response = reader.city(ipAddress);
        if (!hasLocations(response)) {
            return Optional.empty();
        }
        return Optional.of(response);
    } catch (UnknownHostException e) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("UnknownHostException: " + ip);
        }
    } catch (GeoIp2Exception e) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Unexpected GeoIp2Exception: " + e.getMessage());
        }
    } catch (IOException e) {
        LOGGER.warn("Unexpected IOException", e);
    }
    return Optional.empty();
}

From source file:io.dropwizard.maxmind.geoip2.filter.MaxMindGeoIpRequestFilter.java

@Override
public void filter(final ContainerRequestContext containerRequestContext) throws IOException {
    final String clientAddress = containerRequestContext.getHeaders().getFirst(config.getRemoteIpHeader());
    if (Strings.isNullOrEmpty(clientAddress)) {
        return;/*w ww .  j a  va  2s .  co m*/
    }
    log.info("Header: {} | Value: {}", config.getRemoteIpHeader(), clientAddress);
    //Multiple Client ip addresses are being sent in case of multiple people stamping the request
    final String[] addresses = clientAddress.split(",");
    final String clientIp = addresses[0].split(":")[0];
    InetAddress address;
    if (!Strings.isNullOrEmpty(clientIp)) {
        try {
            address = InetAddress.getByName(clientIp);
        } catch (Exception e) {
            log.warn("Cannot resolve address: {} | Error: {}", clientIp, e.getMessage());
            return;
        }
        //Short circuit if there is no ip address
        if (address == null) {
            log.warn("Cannot resolve address: {}", clientIp);
            return;
        }
        try {
            if (config.isEnterprise()) {
                final EnterpriseResponse enterpriseResponse = databaseReader.enterprise(address);
                if (enterpriseResponse == null)
                    return;
                if (enterpriseResponse.getCountry() != null) {
                    addCountryInfo(enterpriseResponse.getCountry(), containerRequestContext);
                }
                if (enterpriseResponse.getMostSpecificSubdivision() != null) {
                    addStateInfo(enterpriseResponse.getMostSpecificSubdivision(), containerRequestContext);
                }
                if (enterpriseResponse.getCity() != null) {
                    addCityInfo(enterpriseResponse.getCity(), containerRequestContext);
                }
                if (enterpriseResponse.getPostal() != null) {
                    addPostalInfo(enterpriseResponse.getPostal(), containerRequestContext);
                }
                if (enterpriseResponse.getLocation() != null) {
                    addLocationInfo(enterpriseResponse.getLocation(), containerRequestContext);
                }
                if (enterpriseResponse.getTraits() != null) {
                    addTraitsInfo(enterpriseResponse.getTraits(), containerRequestContext);
                }
                AnonymousIpResponse anonymousIpResponse = databaseReader.anonymousIp(address);
                if (anonymousIpResponse != null) {
                    anonymousInfo(anonymousIpResponse, containerRequestContext);
                }
            } else {
                switch (config.getType()) {
                case "country":
                    CountryResponse countryResponse = databaseReader.country(address);
                    if (countryResponse != null && countryResponse.getCountry() != null) {
                        addCountryInfo(countryResponse.getCountry(), containerRequestContext);
                    }
                    break;
                case "city":
                    CityResponse cityResponse = databaseReader.city(address);
                    if (cityResponse != null) {
                        if (cityResponse.getCountry() != null) {
                            addCountryInfo(cityResponse.getCountry(), containerRequestContext);
                        }
                        if (cityResponse.getMostSpecificSubdivision() != null) {
                            addStateInfo(cityResponse.getMostSpecificSubdivision(), containerRequestContext);
                        }
                        if (cityResponse.getCity() != null) {
                            addCityInfo(cityResponse.getCity(), containerRequestContext);
                        }
                        if (cityResponse.getPostal() != null) {
                            addPostalInfo(cityResponse.getPostal(), containerRequestContext);
                        }
                        if (cityResponse.getLocation() != null) {
                            addLocationInfo(cityResponse.getLocation(), containerRequestContext);
                        }
                    }
                    break;
                case "anonymous":
                    AnonymousIpResponse anonymousIpResponse = databaseReader.anonymousIp(address);
                    if (anonymousIpResponse != null) {
                        anonymousInfo(anonymousIpResponse, containerRequestContext);
                    }
                }
            }
        } catch (Exception e) {
            log.warn("GeoIP Error: {}", e.getMessage());
        }
    }
}