Example usage for com.google.common.net InetAddresses toAddrString

List of usage examples for com.google.common.net InetAddresses toAddrString

Introduction

In this page you can find the example usage for com.google.common.net InetAddresses toAddrString.

Prototype

public static String toAddrString(InetAddress ip) 

Source Link

Document

Returns the string representation of an InetAddress .

Usage

From source file:org.anarres.dhcp.common.address.AbstractMaskedAddress.java

@Override
public String toString() {
    return InetAddresses.toAddrString(getAddress()) + "/" + getNetmask();
}

From source file:com.google.doubleclick.openrtb.MapperUtil.java

public static String toIpv6String(ByteString bytes) {
    try {// ww  w.j  av a2s . com
        byte[] ipv6 = new byte[16];
        bytes.copyTo(ipv6, 0, 0, min(ipv6.length, bytes.size()));
        return InetAddresses.toAddrString(InetAddress.getByAddress(ipv6));
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("ip=" + BaseEncoding.base16().encode(bytes.toByteArray()));
    }
}

From source file:org.elasticsearch.common.network.NetworkAddress.java

static String format(InetAddress address, int port) {
    Objects.requireNonNull(address);

    StringBuilder builder = new StringBuilder();

    if (port != -1 && address instanceof Inet6Address) {
        builder.append(InetAddresses.toUriString(address));
    } else {//  ww  w  .j a  v  a2  s.com
        builder.append(InetAddresses.toAddrString(address));
    }

    if (port != -1) {
        builder.append(':');
        builder.append(port);
    }

    return builder.toString();
}

From source file:org.n52.shetland.ogc.ows.service.OwsServiceRequestContext.java

private static IPAddress getIPAddress(HttpServletRequest req) {
    InetAddress addr = null;//  w  w  w.  ja  v a 2  s  .c om
    String addrAsString = req.getRemoteAddr();
    try {
        addr = InetAddresses.forString(addrAsString);
    } catch (IllegalArgumentException e) {
        LOG.warn("Ignoring invalid IP address: " + req.getRemoteAddr(), e);
    }

    if (addr instanceof Inet4Address) {
        Inet4Address inet4Address = (Inet4Address) addr;
        return new IPAddress(inet4Address);
    } else if (addr instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) addr;
        // embedded form
        if (InetAddresses.isCompatIPv4Address(inet6Address)) {
            return new IPAddress(InetAddresses.getCompatIPv4Address(inet6Address));
            // mapped form
        } else if (InetAddresses.isMappedIPv4Address(addrAsString)) {
            try {
                return new IPAddress(InetAddress.getByName(addrAsString).getAddress());
            } catch (UnknownHostException e) {
                LOG.warn("Ignoring invalid IPv4-mapped-IPv6 address: " + req.getRemoteAddr(), e);
            }
            // 6to4 addresses
        } else if (InetAddresses.is6to4Address(inet6Address)) {
            return new IPAddress(InetAddresses.get6to4IPv4Address(inet6Address));
        } else if (InetAddresses.toAddrString(addr).equals("::1")) {
            // ::1 is not handled by InetAddresses.isCompatIPv4Address()
            return new IPAddress("127.0.0.1");
        } else {
            LOG.warn("Ignoring not v4 compatible IP address: {}", req.getRemoteAddr());
        }
    } else {
        LOG.warn("Ignoring unknown InetAddress: {}", addr);
    }
    return null;
}

From source file:org.apache.directory.server.dhcp.options.AddressListOption.java

@Override
protected String toStringData() throws DhcpException {
    StringBuilder buf = new StringBuilder("[");
    for (InetAddress address : getAddresses())
        buf.append(" ").append(InetAddresses.toAddrString(address));
    buf.append(" ]");
    return buf.toString();
}

From source file:org.apache.directory.server.dhcp.options.AddressOption.java

@Override
protected String toStringData() throws DhcpException {
    return InetAddresses.toAddrString(getAddress());
}

From source file:org.ftccommunity.enigmabot.LaunchActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);

    Thread.currentThread().setUncaughtExceptionHandler(new RobotUncaughtExceptionHandler(this, 10));
    final Serializable serializableExtra = getIntent()
            .getSerializableExtra(RobotUncaughtExceptionHandler.EXTRA_EMEG_DUMP);
    if (serializableExtra != null) {
        startActivity(new Intent(this, CrashActivity.class)
                .putExtra(RobotUncaughtExceptionHandler.EXTRA_EMEG_DUMP, serializableExtra));
    }/*from   w ww  .  j a  va  2 s  .  c o m*/
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    View main = getWindow().getDecorView();
    main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    dimmer = new Dimmer(getWindow(), 5000, 50);

    // temp
    new Thread(new Runnable() {
        @Override
        public void run() {
            NetworkInterface wlan0;
            try {
                wlan0 = NetworkInterface.getByName("wlan0");
                currentAddress = Collections.list(wlan0.getInetAddresses()).get(1);
                final String ipAddress = InetAddresses.toAddrString(currentAddress);
                Log.i("MAIN:", "IP Address: " + ipAddress);

                // Objects must be held by a synchronized block before calling notify
                synchronized (LaunchActivity.this) {
                    LaunchActivity.this.notifyAll();
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

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();/*w w  w.j ava 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:org.n52.sos.request.RequestContext.java

private static IPAddress getIPAddress(HttpServletRequest req) {
    InetAddress addr = null;//from  w  ww  .j ava2  s  .  c o  m
    try {
        addr = InetAddresses.forString(req.getRemoteAddr());
    } catch (IllegalArgumentException e) {
        LOG.warn("Ignoring invalid IP address: " + req.getRemoteAddr(), e);
    }

    if (addr instanceof Inet4Address) {
        Inet4Address inet4Address = (Inet4Address) addr;
        return new IPAddress(inet4Address);
    } else if (addr instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) addr;
        if (InetAddresses.isCompatIPv4Address(inet6Address)) {
            return new IPAddress(InetAddresses.getCompatIPv4Address(inet6Address));
        } else if (InetAddresses.toAddrString(addr).equals("::1")) {
            // ::1 is not handled by InetAddresses.isCompatIPv4Address()
            return new IPAddress("127.0.0.1");
        } else {
            LOG.warn("Ignoring not v4 compatible IP address: {}", req.getRemoteAddr());
        }
    } else {
        LOG.warn("Ignoring unknown InetAddress: {}", addr);
    }
    return null;
}

From source file:talkeeg.common.core.CurrentAddressesService.java

protected void addAddress(Collection<ClientAddress> addresses, InetAddress address, int netPrefixLen) {
    final int port = this.currentPortSupplier.get();
    addresses.add(/*from  ww  w .  j a  v  a2  s.c o m*/
            new ClientAddress(false, TgAddress.to(InetAddresses.toAddrString(address), netPrefixLen, port)));
    try {
        final InetAddress externalAddress = cache.get(address);
        if (externalAddress != null && !address.equals(externalAddress)) {
            addresses.add(new ClientAddress(true, TgAddress.to(InetAddresses.toAddrString(externalAddress),
                    TgAddress.NO_NETWORK_PREFIX, port)));
        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "can not retrieve external ip for " + address, e);
    }
}