List of usage examples for com.google.common.net InetAddresses forString
public static InetAddress forString(String ipString)
From source file:org.ros.address.InetAddressFactory.java
/** * Creates an {@link InetAddress} with both an IP and a host set so that no * further resolving will take place.// w w w.j av a2 s . com * * If an IP address string is specified, this method ensures that it will be * used in place of a host name. * * If a host name other than {@code Address.LOCALHOST} is specified, this * method trys to find a non-loopback IP associated with the supplied host * name. * * If the specified host name is {@code Address.LOCALHOST}, this method * returns a loopback address. * * @param host * @return an {@link InetAddress} with both an IP and a host set (no further * resolving will take place) */ public static InetAddress newFromHostString(String host) { try { if (InetAddresses.isInetAddress(host)) { return InetAddress.getByAddress(host, InetAddresses.forString(host).getAddress()); } if (host.equals(Address.LOCALHOST)) { return InetAddress.getByAddress(Address.LOCALHOST, InetAddresses.forString(Address.LOOPBACK).getAddress()); } } catch (UnknownHostException e) { throw new RosRuntimeException(e); } Collection<InetAddress> allAddressesByName = getAllInetAddressesByName(host); // First, try to find a non-loopback IPv4 address. for (InetAddress address : allAddressesByName) { if (!address.isLoopbackAddress() && isIpv4(address)) { return address; } } // Return a loopback IPv4 address as a last resort. for (InetAddress address : allAddressesByName) { if (isIpv4(address)) { return address; } } throw new RosRuntimeException("Unable to construct InetAddress for host: " + host); }
From source file:org.opendaylight.lispflowmapping.lisp.serializer.address.Ipv6PrefixSerializer.java
@Override protected void serializeData(ByteBuffer buffer, IpPrefix prefix) { buffer.put(InetAddresses.forString(prefix.getIpv6Prefix().getValue()).getAddress()); }
From source file:org.opendaylight.lispflowmapping.lisp.serializer.address.Ipv4PrefixSerializer.java
@Override protected void serializeData(ByteBuffer buffer, SimpleAddress address) { buffer.put(// w ww . ja va 2 s . c o m InetAddresses.forString(MaskUtil.getAddressStringForIpPrefix(address.getIpPrefix())).getAddress()); }
From source file:org.opendaylight.lispflowmapping.lisp.util.MaskUtil.java
public static Eid normalize(Eid eid, short mask) { Address address = eid.getAddress();// ww w. j a va2 s .c o m try { if (address instanceof Ipv4Prefix) { final String addr = getPrefixAddress(((Ipv4Prefix) address).getIpv4Prefix().getValue()); InetAddress normalized = normalizeIP(InetAddresses.forString(addr), mask); return LispAddressUtil.asIpv4PrefixEid(eid, (Inet4Address) normalized, mask); } else if (address instanceof Ipv6Prefix) { final String addr = getPrefixAddress(((Ipv6Prefix) address).getIpv6Prefix().getValue()); InetAddress normalized = normalizeIP(InetAddresses.forString(addr), mask); return LispAddressUtil.asIpv6PrefixEid(eid, (Inet6Address) normalized, mask); } else if (address instanceof InstanceId) { // TODO - not absolutely necessary, but should be implemented return eid; } } catch (UnknownHostException e) { LOG.warn("Failed to normalize EID {} with mask {}, returning original EID", eid, mask, e); } return eid; }
From source file:org.apache.streams.elasticsearch.ElasticsearchClientManager.java
private synchronized void start() { try {//from w ww . ja v a2 s. co m // We are currently using lazy loading to start the elasticsearch cluster, however. LOGGER.info("Creating a new TransportClient: {}", this.config.getHosts()); Settings settings = Settings.settingsBuilder().put("cluster.name", this.config.getClusterName()) .put("client.transport.ping_timeout", "90s") .put("client.transport.nodes_sampler_interval", "60s").build(); // Create the client client = TransportClient.builder().settings(settings).build(); for (String h : config.getHosts()) { LOGGER.info("Adding Host: {}", h); InetAddress address; if (InetAddresses.isInetAddress(h)) { LOGGER.info("{} is an IP address", h); address = InetAddresses.forString(h); } else { LOGGER.info("{} is a hostname", h); address = InetAddress.getByName(h); } client.addTransportAddress(new InetSocketTransportAddress(address, config.getPort().intValue())); } } catch (Exception ex) { LOGGER.error("Could not Create elasticsearch Transport Client: {}", ex); } }
From source file:io.smartspaces.util.net.InetAddressFactory.java
/** * Creates an {@link InetAddress} with both an IP and a host set so that no * further resolving will take place./* w w w . ja va2 s .com*/ * * If an IP address string is specified, this method ensures that it will be * used in place of a host name. * * If a host name other than {@code Address.LOCALHOST} is specified, this * method trys to find a non-loopback IP associated with the supplied host * name. * * If the specified host name is {@code Address.LOCALHOST}, this method * returns a loopback address. * * @param host * @return an {@link InetAddress} with both an IP and a host set (no further * resolving will take place) */ public static InetAddress newFromHostString(String host) { try { if (InetAddresses.isInetAddress(host)) { return InetAddress.getByAddress(host, InetAddresses.forString(host).getAddress()); } if (host.equals(LOCALHOST)) { return InetAddress.getByAddress(LOCALHOST, InetAddresses.forString(LOOPBACK).getAddress()); } } catch (UnknownHostException e) { throw new SmartSpacesException("Can't get new host from host name " + host, e); } Collection<InetAddress> allAddressesByName = getAllInetAddressesByName(host); // First, try to find a non-loopback IPv4 address. for (InetAddress address : allAddressesByName) { if (!address.isLoopbackAddress() && isIpv4(address)) { return address; } } // Return a loopback IPv4 address as a last resort. for (InetAddress address : allAddressesByName) { if (isIpv4(address)) { return address; } } throw new SmartSpacesException("Unable to construct InetAddress for host: " + host); }
From source file:com.facebook.presto.type.IpAddressOperators.java
@LiteralParameters("x") @ScalarOperator(CAST)/*from ww w .j a va 2 s. co m*/ @SqlType(StandardTypes.IPADDRESS) public static Slice castFromVarcharToIpAddress(@SqlType("varchar(x)") Slice slice) { byte[] address; try { address = InetAddresses.forString(slice.toStringUtf8()).getAddress(); } catch (IllegalArgumentException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, "Cannot cast value to IPADDRESS: " + slice.toStringUtf8()); } byte[] bytes; if (address.length == 4) { bytes = new byte[16]; bytes[10] = (byte) 0xff; bytes[11] = (byte) 0xff; arraycopy(address, 0, bytes, 12, 4); } else if (address.length == 16) { bytes = address; } else { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Invalid InetAddress length: " + address.length); } return wrappedBuffer(bytes); }
From source file:com.github.kryptohash.kryptohashj.core.PeerAddress.java
public static PeerAddress localhost(NetworkParameters params) { return new PeerAddress(InetAddresses.forString("127.0.0.1"), params.getPort()); }
From source file:at.alladin.rmbt.controlServer.RegistrationResource.java
@Post("json") public String request(final String entity) { long startTime = System.currentTimeMillis(); // final String defaultSecret = params.getFirstValue("RMBT_SECRETKEY"); addAllowOrigin();/*from w w w . ja va 2s.c om*/ JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); final InetAddress clientAddress = InetAddresses.forString(clientIpRaw); final String clientIpString = InetAddresses.toAddrString(clientAddress); System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST"), clientIpRaw)); final String geoIpCountry = GeoIPHelper.lookupCountry(clientAddress); // public_ip_asn final Long asn = Helperfunctions.getASN(clientAddress); // public_ip_as_name // country_asn (2 digit country code of AS, eg. AT or EU) final String asName; final String asCountry; if (asn == null) { asName = null; asCountry = null; } else { asName = Helperfunctions.getASName(asn); asCountry = Helperfunctions.getAScountry(asn); } if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); UUID uuid = null; final String uuidString = request.optString("uuid", ""); if (uuidString.length() != 0) uuid = UUID.fromString(uuidString); final String loopModeData = request.optString("loopmode_info", null); LoopModeSettings loopModeSettings = null; final TestLoopModeDao loopModeTestDao = new TestLoopModeDao(conn); if (loopModeData != null) { loopModeSettings = new Gson().fromJson(loopModeData, LoopModeSettings.class); loopModeSettings.setClientUuid(uuidString); loopModeTestDao.save(loopModeSettings); if (1 == 2) throw new LoopModeRejectedException(); } int typeId = 0; final String lang = request.optString("language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } // System.out.println(request.toString(4)); if (conn != null) { final Client clientDb = new Client(conn); if (!request.optString("type").isEmpty()) { typeId = clientDb.getTypeId(request.getString("type")); if (clientDb.hasError()) errorList.addError(clientDb.getError()); } final List<String> clientNames = Arrays .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*")); final List<String> clientVersions = Arrays .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*")); if (clientNames.contains(request.optString("client")) && clientVersions.contains(request.optString("version")) && typeId > 0) { final String clientName = request.getString("client"); final String clientVersion = request.getString("version"); String timeZoneId = request.getString("timezone"); // String tmpTimeZoneId = timeZoneId; final long clientTime = request.getLong("time"); final Timestamp clientTstamp = java.sql.Timestamp .valueOf(new Timestamp(clientTime).toString()); final JSONObject location = request.optJSONObject("location"); long geotime = 0; double geolat = 0; double geolong = 0; float geoaccuracy = 0; double geoaltitude = 0; float geobearing = 0; float geospeed = 0; String geoprovider = ""; if (!request.isNull("location")) { geotime = location.optLong("time", 0); geolat = location.optDouble("lat", 0); geolong = location.optDouble("long", 0); geoaccuracy = (float) location.optDouble("accuracy", 0); geoaltitude = location.optDouble("altitude", 0); geobearing = (float) location.optDouble("bearing", 0); geospeed = (float) location.optDouble("speed", 0); geoprovider = location.optString("provider", ""); } Calendar timeWithZone = null; if (timeZoneId.isEmpty()) { timeZoneId = Helperfunctions.getTimezoneId(); timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); } else timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); long clientUid = 0; /* * if (uuid == null) { * clientDb.setTimeZone(timeWithZone); * clientDb.setTime(tstamp); * clientDb.setClient_type_id(typeId); uuid = * clientDb.storeClient(); if (clientDb.hasError()) { * errorList.addError(clientDb.getError()); } else { * answer.put("uuid", uuid.toString()); } } */ if (errorList.getLength() == 0 && uuid != null) { clientUid = clientDb.getClientByUuid(uuid); if (clientDb.hasError()) errorList.addError(clientDb.getError()); } if (clientUid > 0) { final String testUuid = UUID.randomUUID().toString(); final String testOpenUuid = UUID.randomUUID().toString(); boolean testServerEncryption = true; // encryption is mandatory final String serverType; if (request.optString("client").equals("RMBTws")) serverType = "RMBTws"; else serverType = "RMBT"; final Boolean ipv6; if (clientAddress instanceof Inet6Address) ipv6 = true; else if (clientAddress instanceof Inet4Address) ipv6 = false; else // should never happen, unless ipv > 6 is available ipv6 = null; TestServer server = null; final Boolean userServerSelection = request.optBoolean("user_server_selection"); // It returns false if there is no such key, or if the value is not Boolean.TRUE or the String "true". if (userServerSelection) { final String preferServer = request.optString("prefer_server", null); if (!Strings.isNullOrEmpty(preferServer)) server = getPreferredServer(preferServer, testServerEncryption, ipv6); } if (server == null) server = getNearestServer(errorList, geolat, geolong, geotime, clientIpString, asCountry, geoIpCountry, serverType, testServerEncryption, ipv6); try { if (server == null) throw new JSONException("could not find server"); if (timeZoneId.isEmpty()) { timeZoneId = Helperfunctions.getTimezoneId(); timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); } else timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); answer.put("test_server_address", server.address); answer.put("test_server_port", server.port); answer.put("test_server_name", server.name); answer.put("test_server_encryption", testServerEncryption); answer.put("test_duration", settings.getString("RMBT_DURATION")); answer.put("test_numthreads", settings.getString("RMBT_NUM_THREADS")); answer.put("test_numpings", settings.getString("RMBT_NUM_PINGS")); answer.put("client_remote_ip", clientIpString); final String resultUrl = new Reference(getURL(), settings.getString("RMBT_RESULT_PATH")).getTargetRef().toString(); // System.out.println(resultUrl); answer.put("result_url", resultUrl); final String resultQoSUrl = new Reference(getURL(), settings.getString("RMBT_QOS_RESULT_PATH")).getTargetRef().toString(); // System.out.println(resultUrl); answer.put("result_qos_url", resultQoSUrl); } catch (final JSONException e) { System.out.println("Error generating Answer " + e.toString()); errorList.addError("ERROR_RESPONSE_JSON"); } if (errorList.getLength() == 0) try { PreparedStatement st; st = conn.prepareStatement( "INSERT INTO test(time, uuid, open_test_uuid, client_id, client_name, client_version, client_software_version, client_language, client_public_ip, client_public_ip_anonymized, country_geoip, server_id, port, use_ssl, timezone, client_time, duration, num_threads_requested, status, software_revision, client_test_counter, client_previous_test_status, public_ip_asn, public_ip_as_name, country_asn, public_ip_rdns, run_ndt)" + "VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); int i = 1; // uuid st.setObject(i++, UUID.fromString(testUuid)); // open_test_uuid st.setObject(i++, UUID.fromString(testOpenUuid)); // client_id st.setLong(i++, clientUid); // client_name st.setString(i++, clientName); // client_version st.setString(i++, clientVersion); // client_software_version st.setString(i++, request.optString("softwareVersion", null)); // client_language st.setString(i++, lang); // client_public_ip st.setString(i++, clientIpString); // client_public_ip_anonymized st.setString(i++, Helperfunctions.anonymizeIp(clientAddress)); // country_geoip (2digit country code derived from public IP of client) st.setString(i++, geoIpCountry); // server_id st.setInt(i++, server.id); // port st.setInt(i++, server.port); // use_ssl st.setBoolean(i++, testServerEncryption); // timezone (of client) st.setString(i++, timeZoneId); // client_time (local time of client) st.setTimestamp(i++, clientTstamp, timeWithZone); // duration (requested) st.setInt(i++, Integer.parseInt(settings.getString("RMBT_DURATION"))); // num_threads_requested st.setInt(i++, Integer.parseInt(settings.getString("RMBT_NUM_THREADS"))); // status (of test) st.setString(i++, "STARTED"); //was "RUNNING" before // software_revision (of client) st.setString(i++, request.optString("softwareRevision", null)); // client_test_counter (number of tests the client has performed) final int testCounter = request.optInt("testCounter", -1); if (testCounter == -1) // older clients did not support testCounter st.setNull(i++, Types.INTEGER); else st.setLong(i++, testCounter); // client_previous_test_status (outcome of previous test) st.setString(i++, request.optString("previousTestStatus", null)); // AS name if (asn == null) st.setNull(i++, Types.BIGINT); else st.setLong(i++, asn); if (asName == null) st.setNull(i++, Types.VARCHAR); else st.setString(i++, asName); // AS country if (asCountry == null) st.setNull(i++, Types.VARCHAR); else st.setString(i++, asCountry); //public_ip_rdns String reverseDNS = Helperfunctions.reverseDNSLookup(clientAddress); if (reverseDNS == null || reverseDNS.isEmpty()) st.setNull(i++, Types.VARCHAR); else { reverseDNS = reverseDNS.replaceFirst("\\.$", ""); st.setString(i++, reverseDNS); // cut off last dot (#332) } // run_ndt if (request.has("ndt")) st.setBoolean(i++, request.getBoolean("ndt")); else st.setNull(i++, Types.BOOLEAN); final int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_STORE_TEST"); else { long key = 0; final ResultSet rs = st.getGeneratedKeys(); if (rs.next()) // Retrieve the auto generated // key(s). key = rs.getLong(1); rs.close(); final PreparedStatement getProviderSt = conn .prepareStatement("SELECT rmbt_set_provider_from_as(?)"); getProviderSt.setLong(1, key); String provider = null; if (getProviderSt.execute()) { final ResultSet rs2 = getProviderSt.getResultSet(); if (rs2.next()) provider = rs2.getString(1); } if (provider != null) answer.put("provider", provider); final PreparedStatement testSlotStatement = conn .prepareStatement("SELECT rmbt_get_next_test_slot(?)"); testSlotStatement.setLong(1, key); int testSlot = -1; if (testSlotStatement.execute()) { final ResultSet rs2 = testSlotStatement.getResultSet(); if (rs2.next()) testSlot = rs2.getInt(1); } if (testSlot < 0) errorList.addError("ERROR_DB_STORE_GENERAL"); else { final String data = testUuid + "_" + testSlot; final String hmac = Helperfunctions.calculateHMAC(server.key, data); if (hmac.length() == 0) errorList.addError("ERROR_TEST_TOKEN"); final String token = data + "_" + hmac; final PreparedStatement updateSt = conn .prepareStatement("UPDATE test SET token = ? WHERE uid = ?"); updateSt.setString(1, token); updateSt.setLong(2, key); updateSt.executeUpdate(); answer.put("test_token", token); answer.put("test_uuid", testUuid); answer.put("test_id", key); final long now = System.currentTimeMillis(); int wait = testSlot - (int) (now / 1000); if (wait < 0) wait = 0; answer.put("test_wait", wait); if (geotime != 0 && geolat != 0 && geolong != 0) { final GeoLocation clientLocation = new GeoLocation(conn); clientLocation.setTest_id(key); final Timestamp geotstamp = java.sql.Timestamp .valueOf(new Timestamp(geotime).toString()); clientLocation.setTime(geotstamp, timeZoneId); clientLocation.setAccuracy(geoaccuracy); clientLocation.setAltitude(geoaltitude); clientLocation.setBearing(geobearing); clientLocation.setSpeed(geospeed); clientLocation.setProvider(geoprovider); clientLocation.setGeo_lat(geolat); clientLocation.setGeo_long(geolong); clientLocation.storeLocation(); if (clientLocation.hasError()) errorList.addError(clientLocation.getError()); } } } st.close(); if (loopModeSettings != null) { loopModeSettings.setTestUuid(testUuid); loopModeTestDao.save(loopModeSettings); } } catch (final SQLException e) { errorList.addError("ERROR_DB_STORE_GENERAL"); e.printStackTrace(); } } else errorList.addError("ERROR_CLIENT_UUID"); } else errorList.addError("ERROR_CLIENT_VERSION"); } else errorList.addError("ERROR_DB_CONNECTION"); // System.out.println(answer.toString(4)); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); } catch (SQLException e) { errorList.addError("ERROR_DB_CONNECTION"); e.printStackTrace(); } catch (LoopModeRejectedException e) { errorList.addError("ERROR_REQUEST_REJECTED"); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); answer.putOpt("error_flags", errorList.getErrorFlags()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST_SUCCESS"), clientIpRaw, Long.toString(elapsedTime))); System.out.println(answerString); return answerString; }
From source file:pl.coffeepower.blog.messagebus.fastcast.FastCastModule.java
@Provides @Singleton/*w w w . ja va 2s. c om*/ @Inject private PhysicalTransportConf createPhysicalTransportConf(@NonNull Configuration configuration) { log.info("Creating PhysicalTransportConf with Configuration: {}", configuration); return new PhysicalTransportConf(FastCastConst.STREAM_NAME) .loopBack(InetAddresses.forString(configuration.getBindAddress()).isLoopbackAddress()) .interfaceAdr(configuration.getBindAddress()).mulitcastAdr(configuration.getMulticastAddress()) .port(configuration.getMulticastPort()); }