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

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

Introduction

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

Prototype

public static InetAddress forString(String ipString) 

Source Link

Document

Returns the InetAddress having the given string representation.

Usage

From source file:com.ethlo.geodata.importer.file.FileIpLookupImporter.java

@Override
public long importData() throws IOException {
    final Map.Entry<Date, File> ipDataFile = super.fetchResource(DataType.IP, url);
    final AtomicInteger count = new AtomicInteger(0);

    final File csvFile = ipDataFile.getValue();
    final long total = IoUtils.lineCount(csvFile);
    final ProgressListener prg = new ProgressListener(
            l -> publish(new DataLoadedEvent(this, DataType.IP, Operation.IMPORT, l, total)));

    final IpLookupImporter ipLookupImporter = new IpLookupImporter(csvFile);

    final JsonFactory f = new JsonFactory();
    f.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
    f.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    final ObjectMapper mapper = new ObjectMapper(f);

    final byte newLine = (byte) "\n".charAt(0);

    logger.info("Writing IP data to file {}", getFile().getAbsolutePath());
    try (final OutputStream out = new BufferedOutputStream(new FileOutputStream(getFile()))) {
        ipLookupImporter.processFile(entry -> {
            final String strGeoNameId = findMapValue(entry, "geoname_id", "represented_country_geoname_id",
                    "registered_country_geoname_id");
            final String strGeoNameCountryId = findMapValue(entry, "represented_country_geoname_id",
                    "registered_country_geoname_id");
            final Long geonameId = strGeoNameId != null ? Long.parseLong(strGeoNameId) : null;
            final Long geonameCountryId = strGeoNameCountryId != null ? Long.parseLong(strGeoNameCountryId)
                    : null;/*  w ww . jav a 2  s  .c  o  m*/
            if (geonameId != null) {
                final SubnetUtils u = new SubnetUtils(entry.get("network"));
                final long lower = UnsignedInteger
                        .fromIntBits(InetAddresses
                                .coerceToInteger(InetAddresses.forString(u.getInfo().getLowAddress())))
                        .longValue();
                final long upper = UnsignedInteger
                        .fromIntBits(InetAddresses
                                .coerceToInteger(InetAddresses.forString(u.getInfo().getHighAddress())))
                        .longValue();
                final Map<String, Object> paramMap = new HashMap<>(5);
                paramMap.put("geoname_id", geonameId);
                paramMap.put("geoname_country_id", geonameCountryId);
                paramMap.put("first", lower);
                paramMap.put("last", upper);

                try {
                    mapper.writeValue(out, paramMap);
                    out.write(newLine);
                } catch (IOException exc) {
                    throw new DataAccessResourceFailureException(exc.getMessage(), exc);
                }
            }

            if (count.get() % 100_000 == 0) {
                logger.info("Processed {}", count.get());
            }

            count.getAndIncrement();

            prg.update();
        });
    }

    return total;
}

From source file:org.bitcoinj.core.VersionMessage.java

public VersionMessage(NetworkParameters params, int newBestHeight) {
    super(params);
    clientVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
    localServices = 0;//w ww. j  a  v  a  2s  .c  o m
    time = System.currentTimeMillis() / 1000;
    // Note that the Bitcoin Core doesn't do anything with these, and finding out your own external IP address
    // is kind of tricky anyway, so we just put nonsense here for now.
    InetAddress localhost = InetAddresses.forString("127.0.0.1");
    myAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
    theirAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
    subVer = LIBRARY_SUBVER;
    bestHeight = newBestHeight;
    relayTxesBeforeFilter = true;

    length = 85;
    if (protocolVersion > 31402)
        length += 8;
    length += VarInt.sizeOf(subVer.length()) + subVer.length();
}

From source file:org.opendaylight.protocol.bmp.impl.app.BmpMonitoringStationImpl.java

private void connectMonitoredRouters(final BmpDispatcher dispatcher) {
    if (this.monitoredRouters != null) {
        for (final MonitoredRouter mr : this.monitoredRouters) {
            if (mr.getActive()) {
                Preconditions.checkNotNull(mr.getAddress());
                Preconditions.checkNotNull(mr.getPort());
                final String s = mr.getAddress().getIpv4Address().getValue();
                final InetAddress addr = InetAddresses.forString(s);
                KeyMapping ret = null;/*ww w.  j a  v  a 2s.  com*/
                final Rfc2385Key rfc2385KeyPassword = mr.getPassword();
                ret = KeyMapping.getKeyMapping(addr, rfc2385KeyPassword.getValue());
                dispatcher.createClient(Ipv4Util.toInetSocketAddress(mr.getAddress(), mr.getPort()),
                        this.sessionManager, Optional.<KeyMapping>fromNullable(ret));
            }
        }
    }
}

From source file:google.registry.testing.FullFieldsTestEntityHelper.java

public static HostResource makeHostResource(String fqhn, @Nullable String ip1, @Nullable String ip2) {
    HostResource.Builder builder = new HostResource.Builder().setRepoId(generateNewContactHostRoid())
            .setFullyQualifiedHostName(Idn.toASCII(fqhn))
            .setCreationTimeForTest(DateTime.parse("2000-10-08T00:45:00Z"));
    if ((ip1 != null) || (ip2 != null)) {
        ImmutableSet.Builder<InetAddress> ipBuilder = new ImmutableSet.Builder<>();
        if (ip1 != null) {
            ipBuilder.add(InetAddresses.forString(ip1));
        }/*w w w  .  ja  v  a2 s.c o m*/
        if (ip2 != null) {
            ipBuilder.add(InetAddresses.forString(ip2));
        }
        builder.setInetAddresses(ipBuilder.build());
    }
    return builder.build();
}

From source file:pl.umk.mat.olaf.lobby.lobbythread.LobbyThread.java

/**
 * Find Server addres. Fist looks for chat server on localhost, next checks another interfaces.
 *
 * @throws SocketException the socket exception
 *///from w w w  . j  a  v a 2s.c om
public void findServerAddressAndReceiveInfo() throws SocketException {
    boolean serverFound = true;

    if (serverAddress == null) {
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();

            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    InetAddress addr = address.nextElement();
                    if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress()
                            && !(addr.getHostAddress().indexOf(":") > -1)) {
                        serverAddress = addr.getHostAddress();
                    }
                }
            }
            if (serverAddress == null) {
                serverAddress = "127.0.0.1";
            }
            /**
             * check localhost connection
             */
            System.out.println("Mam ju jaki adres...");
            try {
                clientSocket = new Socket("localhost", port);
            } catch (IOException ex) {

                System.out.println("There is no active severs on the local computer");
                Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                serverFound = false;
            }
            if (serverFound == true) {
                System.out.println("A jednak jest co na localhoscie!");
                try {
                    rooms = returnRoomInfo(clientSocket);
                    serverAddress = "127.0.0.1";
                    clientSocket.close();
                } catch (IOException | ClassNotFoundException ex) {
                    System.out.println("Error while closing socket!!");
                    Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (serverAddress != "127.0.0.1" && !serverFound) {
                System.out.println("nie znalazem na porcie 127.0.0.01, szukam dalej!");
                /**
                 * compute mask, network and broadcast ip address in the network
                 * and
                 * looks for running server
                 */
                int maxMask = ~0;
                mask = maxMask << (32 - NetworkInterface.getByInetAddress(Inet4Address.getByName(serverAddress))
                        .getInterfaceAddresses().get(0).getNetworkPrefixLength());
                networkAddress = InetAddresses.coerceToInteger(InetAddresses.forString(serverAddress)) & mask;
                broadcastAddress = (~mask) | (networkAddress);

                System.out.println("Maska " + InetAddresses.fromInteger(mask).getHostAddress()
                        + " networkAddress " + InetAddresses.fromInteger(networkAddress).getHostAddress()
                        + " broadcast " + InetAddresses.fromInteger(broadcastAddress).getHostAddress());
                /**
                 * check each address between networkAddress and broadcastAddress
                 */
                for (int address = networkAddress + 1; address < broadcastAddress; address++) {
                    System.out.println("Adres: " + InetAddresses.fromInteger(address).getHostAddress());
                    serverFound = true;
                    try {

                        clientSocket = new Socket();
                        clientSocket.connect(new InetSocketAddress(InetAddresses.fromInteger(address), port),
                                250);
                        serverFound = true;
                    } catch (IOException ex) {
                        serverFound = false;
                        Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (serverFound == true) {
                        serverAddress = InetAddresses.fromInteger(address).getHostAddress();
                        try {
                            rooms = returnRoomInfo(clientSocket);
                            clientSocket.close();
                        } catch (IOException | ClassNotFoundException ex) {
                            Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }

                }
            }
            if (serverFound == false) {
                serverAddress = "0.0.0.0";
            }

        } catch (SocketException e) {
            serverAddress = "127.0.0.1";
        } catch (UnknownHostException ex) {
            Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:google.registry.util.CidrAddressBlock.java

/**
 * Attempts to parse the given String and int into a CIDR block.
 *
 * <p>The specified IP address portion must be properly truncated
 * (i.e. all the host bits must be zero) or the input is considered
 * malformed. For example, "1.2.3.0/24" is accepted but "1.2.3.4/24"
 * is not. Similarly, for IPv6, "2001:db8::/32" is accepted whereas
 * "2001:db8::1/32" is not./*w ww  .  j  a  v  a  2  s.c  o  m*/
 *
 * <p>An IP address without a netmask will automatically have the
 * maximum applicable netmask for its address family.  I.e. "1.2.3.4"
 * is automatically treated as "1.2.3.4/32", and "2001:db8::1" is
 * automatically treated as "2001:db8::1/128".
 *
 * <p>If inputs might not be properly truncated but would be acceptable
 * to the application consider constructing a {@code CidrAddressBlock}
 * via {@code create()}.
 *
 * @param ip a String of the form "217.68.0.0" or "2001:db8::".
 * @param netmask an int between 0 and 32 (for IPv4) or 128 (for IPv6).
 *        This is the number of bits, starting from the big end of the IP,
 *        that will be used for network bits (as opposed to host bits)
 *        in this CIDR block.
 *
 * @throws IllegalArgumentException if the params are malformed or do not
 *         represent a valid CIDR block.
 */
public CidrAddressBlock(String ip, int netmask) {
    this(InetAddresses.forString(ip), checkNotNegative(netmask), false);
}

From source file:com.turn.ttorrent.protocol.tracker.http.HTTPAnnounceResponseMessage.java

/**
 * Build a peer list as a list of {@link Peer}s from the
 * announce response's peer list (in non-compact mode).
 *
 * @param peers The list of {@link BEValue}s dictionaries describing the
 * peers from the announce response.//from   w w  w.  ja va  2  s  .  c o  m
 * @return A {@link List} of {@link Peer}s representing the
 * peers' addresses. Peer IDs are lost, but they are not crucial.
 */
@Nonnull
private static void toPeerList(@Nonnull List<Peer> out, @Nonnull List<BEValue> peers) {
    for (BEValue peer : peers) {
        try {
            Map<String, BEValue> peerInfo = peer.getMap();
            String ip = BEUtils.getString(peerInfo.get(PEER_IP));
            int port = BEUtils.getInt(peerInfo.get(PEER_PORT), -1);
            if (ip == null || port < 0) {
                LOG.warn("Invalid peer " + peer);
                continue;
            }
            InetAddress inaddr = InetAddresses.forString(ip);
            InetSocketAddress saddr = new InetSocketAddress(inaddr, port);

            byte[] peerId = BEUtils.getBytes(peerInfo.get(PEER_ID));
            out.add(new Peer(saddr, peerId));
        } catch (InvalidBEncodingException e) {
            LOG.error("Failed to parse peer from " + peer, e);
        } catch (NullPointerException e) {
            LOG.error("Failed to parse peer from " + peer, e);
        } catch (IllegalArgumentException e) {
            LOG.error("Failed to parse peer from " + peer, e);
        }
    }
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.PCCMockCommon.java

static TestingSessionListener checkSessionListenerNotNull(final TestingSessionListenerFactory factory,
        final String localAddress) {
    Stopwatch sw = Stopwatch.createStarted();
    TestingSessionListener listener = null;
    while (sw.elapsed(TimeUnit.SECONDS) <= 1000) {
        listener = factory.getSessionListenerByRemoteAddress(InetAddresses.forString(localAddress));
        if (listener == null) {
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        } else {//  w  w w. ja  v  a2s . c o m
            return listener;
        }
    }
    throw new NullPointerException();
}

From source file:com.eucalyptus.util.dns.DomainNameRecords.java

public static InetAddress inAddrArpaToInetAddress(Name name) {
    final String ipString = new StringBuffer().append(name.getLabelString(3)).append(".")
            .append(name.getLabelString(2)).append(".").append(name.getLabelString(1)).append(".")
            .append(name.getLabelString(0)).toString();
    return InetAddresses.forString(ipString);
}

From source file:org.bitcoinj_extra.core.PeerAddress.java

public static PeerAddress localhost(NetworkParameters params) {
    return new PeerAddress(params, InetAddresses.forString("127.0.0.1"), params.getPort());
}