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

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

Introduction

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

Prototype

public static int coerceToInteger(InetAddress ip) 

Source Link

Document

Returns an integer representing an IPv4 address regardless of whether the supplied argument is an IPv4 address or not.

Usage

From source file:org.squiddev.cctweaks.lua.lib.socket.AddressMatcher.java

public boolean matches(InetAddress address, String host) {
    if (hosts.contains(host))
        return true;
    if (addresses.contains(address))
        return true;

    // Presume true for IPv6 addresses
    if (!(address instanceof Inet4Address))
        return true;

    int value = InetAddresses.coerceToInteger(address);
    for (HostRange range : ranges) {
        if (value >= range.min && value <= range.max)
            return true;
    }//from  www. j  a v  a2 s.co m

    return false;
}

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;//from  w  ww  .  j av  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.opendaylight.genius.idmanager.IdUtils.java

public IdUtils() throws UnknownHostException {
    bladeId = InetAddresses.coerceToInteger(InetAddress.getLocalHost());
}

From source file:org.n52.janmayen.net.IPAddress.java

/**
 * @return the IP address as an 32-bit integer
 *
 * @deprecated {@linkplain  Inet6Address IPv6 addresses} can not be represented by an integer
 *///from w  w  w . ja v  a  2  s.  com
@Deprecated
public int asInt() {
    return InetAddresses.coerceToInteger(this.address);
}

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 2 s . 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:co.cask.cdap.kafka.run.KafkaServerMain.java

private static int generateBrokerId(InetAddress address) {
    LOG.info("Generating broker ID with address {}", address);
    try {/*from ww  w  . j a  v  a 2s . co  m*/
        return Math.abs(InetAddresses.coerceToInteger(address));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.opendaylight.netvirt.sfc.classifier.providers.OpenFlow13Provider.java

public Flow createIngressClassifierAclFlow(NodeId nodeId, MatchBuilder match, Long port, String sffIpStr,
        long nsp, short nsi) {
    OpenFlow13Utils.addMatchInPort(match, nodeId, port);

    Long ipl = InetAddresses.coerceToInteger(InetAddresses.forString(sffIpStr)) & 0xffffffffL;
    List<Action> actionList = new ArrayList<>();
    actionList.add(OpenFlow13Utils.createActionNxPushNsh(actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNshMdtype(NSH_MDTYPE_ONE, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNsp((int) nsp, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNsi(nsi, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNshc1(DEFAULT_NSH_CONTEXT_VALUE, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNshc2(DEFAULT_NSH_CONTEXT_VALUE, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadReg0(ipl, actionList.size()));
    actionList.add(//from   ww  w  . ja v a 2  s.com
            OpenFlow13Utils.createActionResubmitTable(NwConstants.LPORT_DISPATCHER_TABLE, actionList.size()));

    InstructionsBuilder isb = OpenFlow13Utils.wrapActionsIntoApplyActionsInstruction(actionList);

    return OpenFlow13Utils.createFlowBuilder(NwConstants.INGRESS_SFC_CLASSIFIER_ACL_TABLE,
            INGRESS_CLASSIFIER_ACL_PRIORITY, INGRESS_CLASSIFIER_ACL_COOKIE, INGRESS_CLASSIFIER_ACL_FLOW_NAME,
            String.valueOf(flowIdInc.getAndIncrement()), match, isb).build();

}

From source file:com.ethlo.geodata.GeodataServiceImpl.java

@Override
public GeoLocation findByIp(String ip) {
    if (!InetAddresses.isInetAddress(ip)) {
        return null;
    }//from  w w  w  . ja  v  a  2 s.  c  o  m

    final InetAddress address = InetAddresses.forString(ip);
    final boolean isLocalAddress = address.isLoopbackAddress() || address.isAnyLocalAddress();
    if (isLocalAddress) {
        return null;
    }

    final long ipLong = UnsignedInteger.fromIntBits(InetAddresses.coerceToInteger(InetAddresses.forString(ip)))
            .longValue();

    final Long id = ipRanges.get(ipLong);
    return id != null ? findById(id) : null;
}

From source file:org.opendaylight.genius.mdsalutil.MDSALUtil.java

public static BigInteger getBigIntIpFromIpAddress(IpAddress ipAddr) {
    String ipString = ipAddr.getIpv4Address().getValue();
    int ipInt = InetAddresses.coerceToInteger(InetAddresses.forString(ipString));
    return BigInteger.valueOf(ipInt & 0xffffffffL);
}

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

@Override
public int hashCode() {
    return InetAddresses.coerceToInteger(ip);
}