Example usage for java.net InetAddress getClass

List of usage examples for java.net InetAddress getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:Main.java

public static String getLocalIpAddress() {
    try {/* ww  w .j av  a2 s  . c  o m*/
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface intf = en.nextElement();
            String name = intf.getName();
            if (name.compareTo("eth0") == 0 || name.compareTo("wlan0") == 0) {
                Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress.getClass() == Inet4Address.class) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("MY", ex.toString());
    }
    return null;
}

From source file:com.vmware.identity.idm.CommonUtil.java

/**
 * Returns host IP address//from   www.j  ava 2s  .c o  m
 * @return
 * @throws SocketException
 * @throws IOException
 */
public static synchronized String getHostIPAddress(String configDirPath) throws SocketException, IOException {

    ValidateUtil.validateNotEmpty(configDirPath, "configDirPath");
    String configFileName = configDirPath;
    if (configDirPath.endsWith(File.separator) == false) {
        configFileName += File.separator;
    }
    configFileName += HOSTNAME_FILE_NAME;
    String ipAddress = null;
    String CONFIG_IDENTITY_ROOT_KEY = "";
    if (SystemUtils.IS_OS_LINUX) {
        CONFIG_IDENTITY_ROOT_KEY = "Software\\VMware\\Identity\\Configuration";
    } else if (SystemUtils.IS_OS_WINDOWS) {
        CONFIG_IDENTITY_ROOT_KEY = "Software\\VMware\\Identity\\Configuration";
    }
    IRegistryKey registryRootKey = null;

    try {
        IRegistryAdapter registryAdpater = RegistryAdapterFactory.getInstance().getRegistryAdapter();
        registryRootKey = registryAdpater.openRootKey((int) RegKeyAccess.KEY_READ);
        if (registryRootKey == null) {
            throw new NullPointerException("Unable to open Root Key");
        }
        ipAddress = registryAdpater.getStringValue(registryRootKey, CONFIG_IDENTITY_ROOT_KEY, "Hostname", true);
        if (ipAddress == null) {
            ipAddress = ReadHostNameFile(configFileName);
        }
    } catch (Exception ex) {

        // failed to retrieve ipaddress from hostname.txt, fall back to
        // original solution
        ipAddress = null;
        try {
            ipAddress = ReadHostNameFile(configFileName);
        } catch (Exception exp) {
            _logger.info("Failed to read hostname file");
        }

        if (ipAddress == null) {
            ipAddress = findInetAddress(new Predicate<InetAddress>() {
                @Override
                public boolean matches(InetAddress addr) {
                    return ((addr != null) && (addr.getClass() == Inet4Address.class));
                }
            });
        }
        if (ipAddress == null) {
            _logger.info("Failed to find local IPV4 Address.");

            ipAddress = findInetAddress(new Predicate<InetAddress>() {
                @Override
                public boolean matches(InetAddress addr) {
                    return ((addr != null) && (addr.getClass() == Inet6Address.class));
                }
            });

            if (ipAddress == null) {
                _logger.info("Failed to find local IPV6 Address.");
            }
        }

        if (ipAddress == null) {
            logAndThrow("Error : Failed to find local either IPV4 or IPV6 Inet Address.");
        }
    } finally {
        if (registryRootKey != null)
            registryRootKey.close();
    }

    return ipAddress;
}

From source file:com.eislab.af.translator.Translator_hub_i.java

public static boolean ipv6InRange(String localIp, int localMask, String remoteIp) {
    InetAddress remoteAddress = parseAddress(remoteIp);
    InetAddress requiredAddress = parseAddress(localIp);
    int nMaskBits = localMask;

    if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
        return false;
    }//from  w  w  w .  ja va2 s.c  om

    if (nMaskBits <= 0) {
        return remoteAddress.equals(requiredAddress);
    }

    byte[] remAddr = remoteAddress.getAddress();
    byte[] reqAddr = requiredAddress.getAddress();

    int oddBits = nMaskBits % 8;
    int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
    byte[] mask = new byte[nMaskBytes];

    Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);

    if (oddBits != 0) {
        int finalByte = (1 << oddBits) - 1;
        finalByte <<= 8 - oddBits;
        mask[mask.length - 1] = (byte) finalByte;
    }

    //       System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));

    for (int i = 0; i < mask.length; i++) {
        if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
            return false;
        }
    }

    return true;
}

From source file:org.tamacat.httpd.util.IpAddressMatcher.java

public boolean matches(String address) {
    InetAddress remoteAddress = parseAddress(address);
    if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
        return false;
    }/*from   w  w w.  j a  va 2s.c  om*/

    if (nMaskBits < 0) {
        return remoteAddress.equals(requiredAddress);
    }

    byte[] remAddr = remoteAddress.getAddress();
    byte[] reqAddr = requiredAddress.getAddress();

    int oddBits = nMaskBits % 8;
    int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
    byte[] mask = new byte[nMaskBytes];

    Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);

    if (oddBits != 0) {
        int finalByte = (1 << oddBits) - 1;
        finalByte <<= 8 - oddBits;
        mask[mask.length - 1] = (byte) finalByte;
    }

    for (int i = 0; i < mask.length; i++) {
        if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
            return false;
        }
    }
    return true;
}

From source file:org.powertac.tournament.services.TournamentProperties.java

private String getTourneyUrl() {
    if (!properties.getProperty("tourney.location", "").isEmpty()) {
        return properties.getProperty("tourney.location");
    }// w w  w  . j a v a  2  s . c  o m

    String tourneyUrl = "http://%s:8080/TournamentScheduler/";
    String address = "127.0.0.1";
    try {
        Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
        while (n.hasMoreElements()) {
            NetworkInterface e = n.nextElement();
            if (e.getName().startsWith("lo")) {
                continue;
            }

            Enumeration<InetAddress> a = e.getInetAddresses();
            while (a.hasMoreElements()) {
                InetAddress addr = a.nextElement();
                if (addr.getClass().getName().equals("java.net.Inet4Address")) {
                    address = addr.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        messages.add("Error getting Tournament Location!");
    }

    return String.format(tourneyUrl, address);
}

From source file:de.decoit.simu.cbor.ifmap.identifier.CBORIpAddress.java

private void processInetAddress(InetAddress value) {
    if (value == null) {
        throw new IllegalArgumentException("value parameter must not be null");
    }/* w  ww .j  a v  a 2  s  .  c  o m*/

    IfMapIpAddressType localType;
    if (value instanceof Inet4Address) {
        localType = IfMapIpAddressType.IPV4;
    } else if (value instanceof Inet6Address) {
        localType = IfMapIpAddressType.IPV6;
    } else {
        throw new IllegalArgumentException("Unkown type for value parameter: " + value.getClass().getName());
    }

    this.value = value;
    this.type = localType;
}

From source file:nfinity.FindPeer.java

public String ScanNetwork() {
    try {//from  w w w . ja  v a2s  .  c o m
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets)) {
            Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                if (!inetAddress.getClass().toString().equals("class java.net.Inet6Address")) {
                    if (!inetAddress.isLoopbackAddress()) {
                        try {
                            SubnetUtils utils = new SubnetUtils(inetAddress.getHostAddress() + "/"
                                    + netint.getInterfaceAddresses().get(1).getNetworkPrefixLength());
                            String[] allIps = utils.getInfo().getAllAddresses();
                            return ConnectIP(allIps, inetAddress);
                        } catch (IllegalArgumentException ex) {
                            int prefix = NetworkInterface.getByInetAddress(inetAddress).getInterfaceAddresses()
                                    .get(0).getNetworkPrefixLength();
                            if (!inetAddress.isLoopbackAddress()) {
                                System.out
                                        .println("IP: " + inetAddress.getHostAddress() + " Prefix: " + prefix);
                                SubnetUtils utils = new SubnetUtils(
                                        inetAddress.getHostAddress() + "/" + prefix);
                                String[] allIps = utils.getInfo().getAllAddresses();
                                return ConnectIP(allIps, inetAddress);
                            }
                        }
                    }
                }
            }
        }
    } catch (SocketException ex) {
        System.out.println("Connection failed " + ex.getMessage());
    }
    return "Peer not found";
}

From source file:org.blue.star.plugins.check_ping.java

public boolean execute_check() {

    for (String hostname : addresses) {

        try {//from ww  w  .j  a  v a  2s . c  om

            InetAddress inet = InetAddress.getByName(hostname);

            long execute_time = 0;
            long packet_loss = 0;
            for (int pings = 0; pings < max_packets; pings++) {
                boolean reachable = false;
                long ping_time = System.currentTimeMillis();
                if (network_interface != null) {
                    reachable = inet.isReachable(network_interface, 0, utils_h.timeout_interval);
                } else {
                    reachable = inet.isReachable(utils_h.timeout_interval);
                }
                execute_time += (System.currentTimeMillis() - ping_time);
                if (!reachable)
                    packet_loss++;
            }
            rta = execute_time / max_packets;
            pl = (int) packet_loss / max_packets * 100;

            if (verbose > 0) {
                System.out.println("rta = " + rta);
                System.out.println("pl = " + pl);
            }

            if (verbose > 1) {
                System.out.println("isAnyLocalAddress = " + inet.isAnyLocalAddress());
                System.out.println("isLinkLocalAddress = " + inet.isLinkLocalAddress());
                System.out.println("isLoopbackAddress = " + inet.isLoopbackAddress());
                System.out.println("isMCGlobal = " + inet.isMCGlobal());
                System.out.println("isMCLinkLocal = " + inet.isMCLinkLocal());
                System.out.println("isMCNodeLocal = " + inet.isMCNodeLocal());
                System.out.println("isMCOrgLocal = " + inet.isMCOrgLocal());
                System.out.println("isMCSiteLocal = " + inet.isMCSiteLocal());
                System.out.println("isMulticastAddress = " + inet.isMulticastAddress());
                System.out.println("isSiteLocalAddress = " + inet.isSiteLocalAddress());
                System.out.println("isReachable = " + inet.isReachable(utils_h.timeout_interval));
                System.out.println("getCanonicalHostName = " + inet.getCanonicalHostName());
                System.out.println("getHostAddress = " + inet.getHostAddress());
                System.out.println("getHostName = " + inet.getHostName());
                System.out.println("getClass.getName = " + inet.getClass().getName());
            }

            /* The list is only used to check alternatives, if we pass don't do more */
            if (packet_loss != max_packets)
                break;

        } catch (Exception e) {
            warn_text = e.getMessage();
            e.printStackTrace();
        }

    }

    if (pl >= cpl || rta >= crta || rta < 0)
        check_state = common_h.STATE_CRITICAL;
    else if (pl >= wpl || rta >= wrta)
        check_state = common_h.STATE_WARNING;
    else if (pl >= 0 && rta >= 0)
        check_state = common_h.STATE_OK;

    return true;
}

From source file:org.pircbotx.dcc.DCCTest.java

protected void debug(String type, InetAddress address) {
    System.out.println(type + ": " + address + " | Class: " + address.getClass());
}

From source file:org.silverpeas.components.silvercrawler.util.IpAddressMatcher.java

public boolean matches(String address) {
    InetAddress remoteAddress = parseAddress(address);

    if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
        return false;
    }//from  w  w w.  ja v a2 s.c om

    if (nMaskBits < 0) {
        return remoteAddress.equals(requiredAddress);
    }

    byte[] remAddr = remoteAddress.getAddress();
    byte[] reqAddr = requiredAddress.getAddress();

    int oddBits = nMaskBits % 8;
    int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
    byte[] mask = new byte[nMaskBytes];

    Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);

    if (oddBits != 0) {
        int finalByte = (1 << oddBits) - 1;
        finalByte <<= 8 - oddBits;
        mask[mask.length - 1] = (byte) finalByte;
    }

    for (int i = 0; i < mask.length; i++) {
        if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
            return false;
        }
    }

    return true;
}