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:org.opendaylight.lispflowmapping.lisp.util.MaskUtil.java

private static InetAddress normalizeIP(InetAddress address, int maskLength) throws UnknownHostException {
    ByteBuffer byteRepresentation = ByteBuffer.wrap(address.getAddress());
    byte b = (byte) 0xff;
    int mask = maskLength;
    for (int i = 0; i < byteRepresentation.array().length; i++) {
        if (mask >= 8) {
            byteRepresentation.put(i, (byte) (b & byteRepresentation.get(i)));
        } else if (mask > 0) {
            byteRepresentation.put(i, (byte) ((byte) (b << (8 - mask)) & byteRepresentation.get(i)));
        } else {/*  ww w. ja va 2  s  .co m*/
            byteRepresentation.put(i, (byte) (0 & byteRepresentation.get(i)));
        }

        mask -= 8;
    }
    return InetAddress.getByAddress(byteRepresentation.array());
}

From source file:biz.karms.sinkit.ejb.util.CIDRUtils.java

public static ImmutablePair<String, String> getStartEndAddresses(final String cidr)
        throws UnknownHostException {
    //TODO: This is silly. Refactor CIDRUtils so as to accept actual IPs as well as subnets.
    //TODO: Validate the thing before processing. Guava?
    final String fixedCIDR;
    if (!cidr.contains("/")) {
        //IPv6? Hmmm...
        if (cidr.contains(":")) {
            fixedCIDR = cidr + "/128";
        } else {/* www.j ava2 s . c  om*/
            fixedCIDR = cidr + "/32";
        }
    } else {
        fixedCIDR = cidr;
    }
    final int index = fixedCIDR.indexOf("/");
    final InetAddress inetAddress = InetAddress.getByName(fixedCIDR.substring(0, index));
    final int prefixLength = Integer.parseInt(fixedCIDR.substring(index + 1));

    final ByteBuffer maskBuffer;
    if (inetAddress.getAddress().length == 4) {
        maskBuffer = ByteBuffer.allocate(4).putInt(-1);
    } else {
        maskBuffer = ByteBuffer.allocate(16).putLong(-1L).putLong(-1L);
    }

    final BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);
    final ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    final BigInteger ipVal = new BigInteger(1, buffer.array());
    final BigInteger startIp = ipVal.and(mask);
    final BigInteger endIp = startIp.add(mask.not());

    return new ImmutablePair<>(String.format("%040d", startIp), String.format("%040d", endIp));
}

From source file:de.forsthaus.backend.service.impl.IpToCountryServiceImpl.java

/**
 * Converts an ip-address to a long value.<br>
 * /*from w  w  w . jav  a  2 s. co m*/
 * @param address
 * @return
 */
private static long inetAddressToLong(InetAddress address) {
    if (address.isAnyLocalAddress())
        return 0l;

    final byte[] bs;
    if (address instanceof Inet4Address) {
        bs = address.getAddress();
    } else if (address instanceof Inet6Address) {
        if (((Inet6Address) address).isIPv4CompatibleAddress()) {
            // take the last 4 digits
            bs = ArrayUtils.subarray(address.getAddress(), 12, 16);
        } else {
            throw new RuntimeException("IPv6 not supported!");
        }
    } else {
        throw new RuntimeException();
    }

    return bs[0] * 16777216l + bs[1] * 65536 + bs[2] * 256 + bs[3];
}

From source file:com.offbynull.portmapper.common.NetworkUtils.java

/**
 * Convert a IP address to a IPv6 address and dump as a byte array. Essentially, if the input is IPv4 it'll be converted to an
 * IPv4-to-IPv6 address. Otherwise, the IPv6 address will be dumped as-is.
 * @param address address to convert to a ipv6 byte array
 * @return ipv6 byte array//  w  w  w  . j  a  v a  2 s.  c om
 * @throws NullPointerException if any argument is {@code null}
 */
public static byte[] convertToIpv6Array(InetAddress address) {
    Validate.notNull(address);

    byte[] addrArr = address.getAddress();
    switch (addrArr.length) {
    case 4: {
        // convert ipv4 address to ipv4-mapped ipv6 address
        byte[] newAddrArr = new byte[16];
        newAddrArr[10] = (byte) 0xff;
        newAddrArr[11] = (byte) 0xff;
        System.arraycopy(addrArr, 0, newAddrArr, 12, 4);

        return newAddrArr;
    }
    case 16: {
        return addrArr;
    }
    default:
        throw new IllegalStateException();
    }
}

From source file:org.openhab.binding.network.service.NetworkUtils.java

/**
 * Converts IPv4 <tt>InetAddress</tt> to 32 bits int.
 *
 * @param addr IPv4 address object//from  w  ww.  jav a 2 s.c  om
 * @return 32 bits int
 * @throws NullPointerException <tt>addr</tt> is <tt>null</tt>.
 * @throws IllegalArgumentException the address is not IPv4 (Inet4Address).
 */
public static final int inetAddress2Int(InetAddress addr) {
    if (!(addr instanceof Inet4Address)) {
        throw new IllegalArgumentException("Only IPv4 supported");
    }

    byte[] addrBytes = addr.getAddress();
    return ((addrBytes[0] & 0xFF) << 24) | ((addrBytes[1] & 0xFF) << 16) | ((addrBytes[2] & 0xFF) << 8)
            | ((addrBytes[3] & 0xFF));
}

From source file:net.unicon.academus.apps.download.DownloadServiceFileSystem.java

/**
 * Generate a unique host identifier using the host's IP address.
 * @return unique host identifier/*  ww w .j  a  v a2s  . c o  m*/
 */
private static long generateHostIdentifier() {
    long hostId;
    InetAddress lhost = null;
    try {
        lhost = InetAddress.getLocalHost();
        byte[] addr = lhost.getAddress();
        hostId = ((addr[0] & 0xff) << 24) + ((addr[1] & 0xff) << 16) + ((addr[2] & 0xff) << 8)
                + (addr[3] & 0xff);
    } catch (UnknownHostException e) {
        e.printStackTrace();
        hostId = -1;
    }
    if (log.isDebugEnabled()) {
        log.debug("System host identifier: " + hostId);
    }
    return hostId;
}

From source file:GUIDGenerator.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.
 *
 * Usage: Add an id field (type java.lang.String) to your EJB, and add setId(XXXUtil.generateGUID(this)); to the ejbCreate method.
 *//*w  w  w  . j a v  a 2s .c o m*/
public static final String generateGUID(Object o) {
    StringBuffer tmpBuffer = new StringBuffer(16);
    if (hexServerIP == null) {
        java.net.InetAddress localInetAddress = null;
        try {
            localInetAddress = java.net.InetAddress.getLocalHost();
        } catch (java.net.UnknownHostException uhe) {
            return null;
        }
        byte serverIP[] = localInetAddress.getAddress();
        hexServerIP = hexFormat(getInt(serverIP), 8);
    }

    String hashcode = hexFormat(System.identityHashCode(o), 8);
    tmpBuffer.append(hexServerIP);
    tmpBuffer.append(hashcode);

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

    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:com.legstar.test.cixs.AbstractHttpClientTester.java

/**
 * Assuming the local machine is running JBoss ESB.
 * /*from w  w w  . j  av  a  2s .c o m*/
 * @return the local machine IP address
 */
protected static String getLocalIPAddress() {
    try {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
        return ipAddrStr;
    } catch (UnknownHostException e) {
        return "";
    }

}

From source file:org.bml.util.geo.util.geolite.GISData.java

private static void setInetAddress(PreparedStatement ps, String ipAddress)
        throws SQLException, UnknownHostException {
    if (ipAddress == null || ipAddress.isEmpty()) {
        return;//from w w w.j  a v  a  2  s . co  m
    }
    InetAddress ip;
    try {
        ip = InetAddress.getByName(ipAddress);
        ps.setInt(1, ConversionUtils.byteArrayToUnsignedInt(ip.getAddress()));
    } catch (UnknownHostException ex) {
        LOG.warn("UnknownHostException Found while converting IPV4 adress to unsigned int.", ex);
        throw ex;
    }
}

From source file:otsopack.commons.network.coordination.spacemanager.HttpSpaceManager.java

public static String getIpAddress() {
    try {/*from  w w w .  ja  v  a2s  .  c o m*/
        final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netIf : Collections.list(nets)) {
            // If the network is active
            if (isUp(netIf)) {
                Enumeration<InetAddress> addresses = netIf.getInetAddresses();
                for (InetAddress addr : Collections.list(addresses))
                    // If the IP address is IPv4 and it's not the local address, store it
                    if (addr.getAddress().length == 4 && !addr.isLoopbackAddress())
                        return addr.getHostAddress();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}