Example usage for java.net InetAddress getAddress

List of usage examples for java.net InetAddress getAddress

Introduction

In this page you can find the example usage for java.net InetAddress getAddress.

Prototype

public byte[] getAddress() 

Source Link

Document

Returns the raw IP address of this InetAddress object.

Usage

From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java

/**
 * Return <code>true</code> if the specified client and server addresses
 * are the same.  This method works around a bug in the IBM 1.1.8 JVM on
 * Linux, where the address bytes are returned reversed in some
 * circumstances.//from  w ww  . java2 s .c o m
 *
 * @param server The server's InetAddress
 * @param client The client's InetAddress
 */
public static boolean isSameAddress(InetAddress server, InetAddress client) {
    // Compare the byte array versions of the two addresses
    byte serverAddr[] = server.getAddress();
    byte clientAddr[] = client.getAddress();
    if (serverAddr.length != clientAddr.length) {
        return (false);
    }
    boolean match = true;
    for (int i = 0; i < serverAddr.length; i++) {
        if (serverAddr[i] != clientAddr[i]) {
            match = false;
            break;
        }
    }
    if (match) {
        return (true);
    }

    // Compare the reversed form of the two addresses
    for (int i = 0; i < serverAddr.length; i++) {
        if (serverAddr[i] != clientAddr[(serverAddr.length - 1) - i]) {
            return (false);
        }
    }
    return (true);
}

From source file:org.springframework.data.hadoop.util.net.DefaultHostInfoDiscovery.java

private List<InetAddress> filterAddresses(List<InetAddress> addresses) {
    List<InetAddress> filtered = new ArrayList<InetAddress>();
    for (InetAddress address : addresses) {
        // take only ipv4 addresses whose byte array length is always 4
        boolean match = address.getAddress() != null && address.getAddress().length == 4;

        // check loopback
        if (!loopback && address.isLoopbackAddress()) {
            match = false;//from w w  w  .j av a  2  s .  co m
        }

        // match cidr if defined
        if (match && StringUtils.hasText(matchIpv4)) {
            match = matchIpv4(matchIpv4, address.getHostAddress());
        }

        if (match) {
            filtered.add(address);
        }
    }
    return filtered;
}

From source file:com.ok2c.lightmtp.util.InetAddressRange.java

public InetAddressRange(final InetAddress address, final int mask) {
    super();/*from   w ww  . j a v  a 2 s  .  c  o m*/
    Args.notNull(address, "Address");
    if (mask < 0) {
        throw new IllegalArgumentException("Address mask may not be negative");
    }
    this.address = address;
    this.mask = mask;

    byte[] addr = address.getAddress();
    BigInteger bigint = new BigInteger(addr);
    int shiftBy = 0;
    if (mask > 0) {
        if (addr.length == 4) {
            shiftBy = 32 - mask;
        } else if (addr.length == 16) {
            shiftBy = 128 - mask;
        } else {
            throw new IllegalArgumentException("Unsupported address: " + address);
        }
    }
    if (shiftBy > 0) {
        bigint = bigint.shiftRight(shiftBy);
    }
    this.bigint = bigint;
    this.shiftBy = shiftBy;
}

From source file:org.opennms.netmgt.model.discovery.IPAddrRange.java

/**
 * <P>// ww  w  .  j a va  2  s .  c om
 * Creates a new IPAddressRange object that can be used to encapsulate a
 * contiguous range of IP Addresses. Once created the object can be used to
 * get either an Iterator or Enumeration object to cycle through the list of
 * address encapsulated by this object.
 * </P>
 * 
 * <P>
 * It is important to note that if the address for start is greater than
 * end, the values will be swapped so that the iteration is always from the
 * lowest address to the highest address.
 * </P>
 * 
 * @param start
 *            The starting address.
 * @param end
 *            The ending address.
 * 
 */
IPAddrRange(InetAddress start, InetAddress end) {
    byte[] from = start.getAddress();
    byte[] to = end.getAddress();

    if (new ByteArrayComparator().compare(from, to) > 0) {
        LOG.warn(
                "The beginning of the address range is greater than the end of the address range ({} - {}), swapping values to create a valid IP address range",
                InetAddressUtils.str(start), InetAddressUtils.str(end));
        m_end = from;
        m_begin = to;
    } else {
        m_begin = from;
        m_end = to;
    }
}

From source file:org.opennms.netmgt.model.discovery.IPAddrRange.java

/**
 * This method may be used to determine if the specified IP address is
 * contained within the IP address range.
 * //  ww  w. ja  va2s .c o  m
 * @param ipAddr
 *            IP address (InetAddress) to compare
 * 
 * @return 'true' if the specified IP address falls within the IP address
 *         range. 'false' otherwise.
 */
boolean contains(InetAddress ipAddr) {
    return InetAddressUtils.isInetAddressInRange(ipAddr.getAddress(), m_begin, m_end);
}

From source file:org.commoncrawl.hadoop.io.S3GetMetdataJob.java

public void map(Text key, ArcFileItem value, OutputCollector<Text, CrawlURLMetadata> output, Reporter reporter)
        throws IOException {

    try {/*from   w w  w.  j av a 2s .co  m*/
        // create a url metadata
        CrawlURLMetadata urlMetadataOut = new CrawlURLMetadata();

        // set direct fields ...

        // set arc file metadata fields ...
        urlMetadataOut.setArcFileName(value.getArcFileName());
        urlMetadataOut.setArcFileOffset(value.getArcFilePos());
        // set ip field ..
        InetAddress address = InetAddress.getByName(value.getHostIP());
        urlMetadataOut.setServerIP(IPAddressUtils.IPV4AddressToInteger(address.getAddress()));
        // set fetch length
        urlMetadataOut.setLastFetchSize(value.getContent().getCount());

        // walk headers ...
        for (ArcFileHeaderItem headerItem : value.getHeaderItems()) {
            if (headerItem.getItemKey().equalsIgnoreCase(ARCFileHeader_ParseSegmentId)) {
                urlMetadataOut.setParseDataSegNo(Integer.parseInt(headerItem.getItemValue()));
            } else if (headerItem.getItemKey().equalsIgnoreCase("Content-Type")) {
                urlMetadataOut.setContentType(headerItem.getItemValue());
            } else if (headerItem.getItemKey().equalsIgnoreCase("Content-Length")) {
                urlMetadataOut.setContentLength(Integer.parseInt((headerItem.getItemValue())));
            } else if (headerItem.getItemKey().equalsIgnoreCase(ARCFileHeader_URLFP)) {
                urlMetadataOut.setUrlFP(Long.parseLong(headerItem.getItemValue()));
            } else if (headerItem.getItemKey().equalsIgnoreCase(ARCFileHeader_HostFP)) {
                urlMetadataOut.setHostFP(Long.parseLong(headerItem.getItemValue()));
            } else if (headerItem.getItemKey().equalsIgnoreCase(ARCFileHeader_Signature)) {
                urlMetadataOut.setSignature(headerItem.getItemValue());
            } else if (headerItem.getItemKey().equalsIgnoreCase(ARCFileHeader_CrawlNumber)) {
                urlMetadataOut.setCrawlNumber(Integer.parseInt(headerItem.getItemValue()));
            } else if (headerItem.getItemKey().equalsIgnoreCase(ARCFileHeader_FetchTimeStamp)) {
                urlMetadataOut.setLastFetchTimestamp(Long.parseLong(headerItem.getItemValue()));
            }
        }

        if (output != null) {
            output.collect(key, urlMetadataOut);
        }
    }
    // catch any type of exception and log it ONLY for now
    catch (Exception e) {

    }
}

From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java

private InetAddress[] resolveInternal(String originalHost, String host) throws IOException {
    if (isValidIpAddress(host))
        return fromAddressString(originalHost, host);
    // First, I'll try to load address cached.
    if (mHostCache.containsKey(host)) {
        final InetAddress[] hostAddr = mHostCache.get(host);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got cached " + Arrays.toString(hostAddr));
        }//w  ww . j a  v  a  2 s .  co m
        return hostAddr;
    }
    // Then I'll try to load from custom host mapping.
    // Stupid way to find top domain, but really fast.
    if (mHostMapping.contains(host)) {
        final String mappedAddr = mHostMapping.getString(host, null);
        if (mappedAddr != null) {
            final InetAddress[] hostAddr = fromAddressString(originalHost, mappedAddr);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Got mapped " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
    }
    mSystemHosts.reloadIfNeeded();
    if (mSystemHosts.contains(host)) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, mSystemHosts.getAddress(host));
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got hosts " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    final String customMappedHost = findHost(host);
    if (customMappedHost != null) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, customMappedHost);
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + customMappedHost + " for host " + host);
        }
        return hostAddr;
    }
    // Use TCP DNS Query if enabled.
    final Resolver dns = getResolver();
    if (dns != null && mPreferences.getBoolean(KEY_TCP_DNS_QUERY, false)) {
        final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
        final Record[] records;
        lookup.setResolver(dns);
        lookup.run();
        final int result = lookup.getResult();
        if (result != Lookup.SUCCESSFUL) {
            throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
        }
        records = lookup.getAnswers();
        final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
        // Test each IP address resolved.
        for (final Record record : records) {
            if (record instanceof ARecord) {
                final InetAddress ipv4Addr = ((ARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
            } else if (record instanceof AAAARecord) {
                final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
            }
        }
        if (!resolvedAddresses.isEmpty()) {
            final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
        // No address is reachable, but I believe the IP is correct.

        for (final Record record : records) {
            if (record instanceof CNAMERecord)
                return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString());
        }
    }
    if (Utils.isDebugBuild()) {
        Log.w(RESOLVER_LOGTAG, "Resolve address " + host + " failed, using original host");
    }
    final InetAddress[] defaultAddresses = InetAddress.getAllByName(host);
    mHostCache.put(host, defaultAddresses);
    return defaultAddresses;
}

From source file:org.eclipse.smila.utils.xml.XMLUtils.java

/**
 * A 32 byte GUID generator (Globally Unique ID). These artificial keys SHOULD <strong>NOT </strong> be seen by the
 * user, not even touched by the DBA but with very rare exceptions, just manipulated by the database and the programs.
 * /*from   ww w.j  a  v  a 2  s. c om*/
 * Usage: Add an id field (type java.lang.String) to your EJB, and add setId(XXXUtil.generateGUID(this)); to the
 * ejbCreate method.
 * 
 * @return String
 * @param o
 *          -
 */
public static final String generateGUID(Object o) {
    final Log log = LogFactory.getLog(XMLUtils.class);
    final StringBuffer tmpBuffer = new StringBuffer(16);
    if (s_hexServerIP == null) {
        java.net.InetAddress localInetAddress = null;
        try {
            // get the inet address
            localInetAddress = java.net.InetAddress.getLocalHost();
        } catch (final java.net.UnknownHostException uhe) {
            if (log.isErrorEnabled()) {
                log.error(
                        "ConfigurationUtil: Could not get the local IP address using InetAddress.getLocalHost()!",
                        uhe);
            }
            return null;
        }
        final byte[] serverIP = localInetAddress.getAddress();
        s_hexServerIP = hexFormat(getInt(serverIP), 8);
    }
    final String hashcode = hexFormat(System.identityHashCode(o), 8);
    tmpBuffer.append(s_hexServerIP);
    tmpBuffer.append(hashcode);

    final long timeNow = System.currentTimeMillis();
    final int timeLow = (int) timeNow & 0xFFFFFFFF;
    final int node = SEEDER.nextInt();

    final StringBuffer guid = new StringBuffer(32);
    guid.append(hexFormat(timeLow, 8));
    guid.append(tmpBuffer.toString());
    guid.append(hexFormat(node, 8));
    return guid.toString();
}

From source file:org.java.plugin.boot.ControlThread.java

private boolean isValidRemoteHost(final InetAddress addr) {
    byte[] localAddr = serverSocket.getInetAddress().getAddress();
    byte[] remoteAddr = addr.getAddress();
    if (localAddr.length != remoteAddr.length) {
        return false;
    }//from w w  w. j av a 2  s.c  om
    for (int i = 0; i < remoteAddr.length; i++) {
        if (localAddr[i] != remoteAddr[i]) {
            return false;
        }
    }
    return true;
}

From source file:com.jagornet.dhcp.db.JdbcIaAddressDAO.java

public IaAddress getByInetAddress(InetAddress inetAddr) {
    return getJdbcTemplate().queryForObject("select * from iaaddress where ipaddress = ?",
            new IaAddrRowMapper(), inetAddr.getAddress());
}