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:at.alladin.rmbt.shared.Helperfunctions.java

public static Name getReverseIPName(final InetAddress adr, final Name postfix) {
    final byte[] addr = adr.getAddress();
    final StringBuilder sb = new StringBuilder();
    if (addr.length == 4)
        for (int i = addr.length - 1; i >= 0; i--) {
            sb.append(addr[i] & 0xFF);
            if (i > 0)
                sb.append(".");
        }/*from  w  w w .  j a  v  a  2s  . c o m*/
    else {
        final int[] nibbles = new int[2];
        for (int i = addr.length - 1; i >= 0; i--) {
            nibbles[0] = (addr[i] & 0xFF) >> 4;
            nibbles[1] = addr[i] & 0xFF & 0xF;
            for (int j = nibbles.length - 1; j >= 0; j--) {
                sb.append(Integer.toHexString(nibbles[j]));
                if (i > 0 || j > 0)
                    sb.append(".");
            }
        }
    }
    try {
        return Name.fromString(sb.toString(), postfix);
    } catch (final TextParseException e) {
        throw new IllegalStateException("name cannot be invalid");
    }
}

From source file:at.alladin.rmbt.shared.Helperfunctions.java

public static String anonymizeIp(final InetAddress inetAddress) {
    try {// w  w w .j a va2  s.co  m
        final byte[] address = inetAddress.getAddress();
        address[address.length - 1] = 0;
        if (address.length > 4) // ipv6
        {
            for (int i = 6; i < address.length; i++)
                address[i] = 0;
        }

        String result = InetAddresses.toAddrString(InetAddress.getByAddress(address));
        if (address.length == 4)
            result = result.replaceFirst(".0$", "");
        return result;
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.clustercontrol.repository.util.NodeSearchUtil.java

/**
 * Generate default IP for node search/create dialog
 *///from ww w .j  a  va2s .  co m
public static String generateDefaultIp(String def, int hostAddress) {
    try {
        // Get IP
        InetAddress addr = Inet4Address.getLocalHost();

        // Get subnet mask length
        int prefixLength = -1;
        NetworkInterface ni = NetworkInterface.getByInetAddress(addr);
        for (InterfaceAddress iaddr : ni.getInterfaceAddresses()) {
            if (iaddr.getAddress() instanceof Inet4Address) {
                prefixLength = iaddr.getNetworkPrefixLength();
                break;
            }
        }
        if (-1 == prefixLength) {
            return def;
        }

        byte[] ipRaw = addr.getAddress();
        // For ipv4
        if (4 == ipRaw.length) {
            int counter = prefixLength;
            for (int i = 0; i < ipRaw.length; i++) {
                if (counter < 8) {
                    byte mask = 0x00;
                    for (int j = 0; j < counter; j++) {
                        mask = (byte) (mask >> 1 | 0x80);
                    }
                    ipRaw[i] = (byte) (ipRaw[i] & mask);
                }
                counter -= 8;
            }

            // Re-format/round up hostAddress
            if (hostAddress < 0) {
                hostAddress += Math.pow(2, 32 - prefixLength);
            }

            // Add host address part
            int part = 4;
            while (hostAddress > 0 && part > 0) {
                ipRaw[part - 1] += (hostAddress & 0xff);
                hostAddress >>= 8;
            }
            return Inet4Address.getByAddress(ipRaw).getHostAddress();
        }
        // TODO Support ipv6?
    } catch (UnknownHostException | SocketException e) {
        m_log.debug(e);
    }
    return def;
}

From source file:com.git.original.common.utils.IPUtils.java

/**
 * ?IP?/*from ww  w.  j  ava  2s .c o  m*/
 * <p>
 * :<br/>
 * 1. 192.xxx.xxx.xxx<br>
 * 2. 172.xxx.xxx.xxx<br>
 * 3. 10.xxx.xxx.xxx<br>
 * other<br>
 * 
 * @return ipv4?
 * @throws SocketException
 */
private static synchronized int doGetLocalIp() throws SocketException {
    if (localIp != 0) {
        return localIp;
    }

    Integer ipStartWith10 = null;
    Integer ipStartWith172 = null;
    Integer other = null;

    /*
     * ?IP?
     */
    Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces();
    while (interfaceEnum.hasMoreElements()) {
        NetworkInterface netInterface = interfaceEnum.nextElement();
        if (!netInterface.isUp()) {
            continue;
        }

        Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses();
        while (addrEnum.hasMoreElements()) {
            InetAddress addr = addrEnum.nextElement();
            String hostAddr = addr.getHostAddress();

            if (hostAddr.startsWith("192.")) {
                localIp = ByteUtils.toInt(addr.getAddress());
                return localIp;
            } else if (ipStartWith172 == null && hostAddr.startsWith("172.")) {
                ipStartWith172 = ByteUtils.toInt(addr.getAddress());
            } else if (ipStartWith10 == null && hostAddr.startsWith("10.")) {
                ipStartWith10 = ByteUtils.toInt(addr.getAddress());
            } else if (other == null && (addr instanceof Inet4Address)) {
                other = ByteUtils.toInt(addr.getAddress());
            }
        }
    }

    if (ipStartWith172 != null) {
        localIp = ipStartWith172;
        return localIp;
    } else if (ipStartWith10 != null) {
        localIp = ipStartWith10;
        return localIp;
    } else if (other != null) {
        localIp = other;
        return localIp;
    }

    throw new RuntimeException("can not get Local Server IPv4 Address");
}

From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java

@SuppressWarnings("TryWithIdenticalCatches")
protected static boolean checkRouteToHost(Context context, String host, boolean usingMmsRadio)
        throws IOException {
    InetAddress inetAddress = InetAddress.getByName(host);
    if (!usingMmsRadio) {
        if (inetAddress.isSiteLocalAddress()) {
            throw new IOException("RFC1918 address in non-MMS radio situation!");
        }/*  w ww . j a v  a 2  s. c om*/
        Log.w(TAG, "returning vacuous success since MMS radio is not in use");
        return true;
    }

    if (inetAddress == null) {
        throw new IOException("Unable to lookup host: InetAddress.getByName() returned null.");
    }

    byte[] ipAddressBytes = inetAddress.getAddress();
    if (ipAddressBytes == null) {
        Log.w(TAG, "resolved IP address bytes are null, returning true to attempt a connection anyway.");
        return true;
    }

    Log.w(TAG, "Checking route to address: " + host + ", " + inetAddress.getHostAddress());
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        final Method requestRouteMethod = manager.getClass().getMethod("requestRouteToHostAddress",
                Integer.TYPE, InetAddress.class);
        final boolean routeToHostObtained = (Boolean) requestRouteMethod.invoke(manager,
                MmsRadio.TYPE_MOBILE_MMS, inetAddress);
        Log.w(TAG, "requestRouteToHostAddress(" + inetAddress + ") -> " + routeToHostObtained);
        return routeToHostObtained;
    } catch (NoSuchMethodException nsme) {
        Log.w(TAG, nsme);
    } catch (IllegalAccessException iae) {
        Log.w(TAG, iae);
    } catch (InvocationTargetException ite) {
        Log.w(TAG, ite);
    }

    final int ipAddress = Conversions.byteArrayToIntLittleEndian(ipAddressBytes, 0);
    final boolean routeToHostObtained = manager.requestRouteToHost(MmsRadio.TYPE_MOBILE_MMS, ipAddress);
    Log.w(TAG, "requestRouteToHost(" + ipAddress + ") -> " + routeToHostObtained);
    return routeToHostObtained;
}

From source file:com.bigdata.dastor.service.StorageProxy.java

private static void addHintHeader(Message message, InetAddress target) {
    byte[] oldHint = message.getHeader(RowMutation.HINT);
    byte[] hint = oldHint == null ? target.getAddress() : ArrayUtils.addAll(oldHint, target.getAddress());
    message.setHeader(RowMutation.HINT, hint);
}

From source file:org.cesecore.util.StringTools.java

/**
 * Converts an IP-address string to octets of binary ints. ipv4 is of form a.b.c.d, i.e. at least four octets for example 192.168.5.54 ipv6 is of
 * form a:b:c:d:e:f:g:h, for example 2001:0db8:85a3:0000:0000:8a2e:0370:7334
 * //from  w  w  w .  j  ava 2 s . c  o m
 * Result is tested with openssl, that it's subjectAltName displays as intended.
 * 
 * @param str string form of ip-address
 * @return octets, empty array if input format is invalid, never null
 */
public static byte[] ipStringToOctets(final String str) {
    byte[] ret = null;
    if (StringTools.isIpAddress(str)) {
        try {
            final InetAddress adr = InetAddress.getByName(str);
            ret = adr.getAddress();
        } catch (UnknownHostException e) {
            log.info("Error parsing ip address (ipv4 or ipv6): ", e);
        }
    }
    if (ret == null) {
        log.info("Not a IPv4 or IPv6 address, returning empty array.");
        ret = new byte[0];
    }
    return ret;
}

From source file:org.apache.hadoop.net.NetUtils.java

/**
 * Create a socket address with the given host and port.  The hostname
 * might be replaced with another host that was set via
 * {@link #addStaticResolution(String, String)}.  The value of
 * hadoop.security.token.service.use_ip will determine whether the
 * standard java host resolver is used, or if the fully qualified resolver
 * is used.// ww  w  .ja va  2 s.  c  om
 * @param host the hostname or IP use to instantiate the object
 * @param port the port number
 * @return InetSocketAddress
 */
public static InetSocketAddress makeSocketAddr(String host, int port) {
    String staticHost = getStaticResolution(host);
    String resolveHost = (staticHost != null) ? staticHost : host;

    InetSocketAddress addr;
    try {
        InetAddress iaddr = SecurityUtil.getByName(resolveHost);
        // if there is a static entry for the host, make the returned
        // address look like the original given host
        if (staticHost != null) {
            iaddr = InetAddress.getByAddress(host, iaddr.getAddress());
        }
        addr = new InetSocketAddress(iaddr, port);
    } catch (UnknownHostException e) {
        addr = InetSocketAddress.createUnresolved(host, port);
    }
    return addr;
}

From source file:org.thoughtcrime.securesms.mms.LegacyMmsConnection.java

@SuppressWarnings("TryWithIdenticalCatches")
protected static boolean checkRouteToHost(Context context, String host, boolean usingMmsRadio)
        throws IOException {
    InetAddress inetAddress = InetAddress.getByName(host);
    if (!usingMmsRadio) {
        if (inetAddress.isSiteLocalAddress()) {
            throw new IOException("RFC1918 address in non-MMS radio situation!");
        }/*from   w w w  . j  av a  2 s  .c o  m*/
        Log.w(TAG, "returning vacuous success since MMS radio is not in use");
        return true;
    }

    if (inetAddress == null) {
        throw new IOException("Unable to lookup host: InetAddress.getByName() returned null.");
    }

    byte[] ipAddressBytes = inetAddress.getAddress();
    if (ipAddressBytes == null) {
        Log.w(TAG, "resolved IP address bytes are null, returning true to attempt a connection anyway.");
        return true;
    }

    Log.i(TAG, "Checking route to address: " + host + ", " + inetAddress.getHostAddress());
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    try {
        final Method requestRouteMethod = manager.getClass().getMethod("requestRouteToHostAddress",
                Integer.TYPE, InetAddress.class);
        final boolean routeToHostObtained = (Boolean) requestRouteMethod.invoke(manager,
                MmsRadio.TYPE_MOBILE_MMS, inetAddress);
        Log.i(TAG, "requestRouteToHostAddress(" + inetAddress + ") -> " + routeToHostObtained);
        return routeToHostObtained;
    } catch (NoSuchMethodException nsme) {
        Log.w(TAG, nsme);
    } catch (IllegalAccessException iae) {
        Log.w(TAG, iae);
    } catch (InvocationTargetException ite) {
        Log.w(TAG, ite);
    }

    return false;
}

From source file:org.apache.jk.common.ChannelSocket.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 w  w  . j a v  a2 s  .  co  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);
}