Example usage for java.net InetAddress isLinkLocalAddress

List of usage examples for java.net InetAddress isLinkLocalAddress

Introduction

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

Prototype

public boolean isLinkLocalAddress() 

Source Link

Document

Utility routine to check if the InetAddress is an link local address.

Usage

From source file:org.apache.sshd.common.util.net.SshdSocketAddress.java

/**
 * @param addr The {@link InetAddress} to be verified
 * @return <P><code>true</code> if the address is:</P></BR>
 * <UL>//w  w w.ja  v a  2  s . c  o m
 *         <LI>Not <code>null</code></LI>
 *         <LI>An {@link Inet4Address}</LI>
 *         <LI>Not link local</LI>
 *         <LI>Not a multicast</LI>
 *         <LI>Not a loopback</LI>
 * </UL>
 * @see InetAddress#isLinkLocalAddress()
 * @see InetAddress#isMulticastAddress()
 * @see InetAddress#isMulticastAddress()
 */
public static boolean isValidHostAddress(InetAddress addr) {
    if (addr == null) {
        return false;
    }

    if (addr.isLinkLocalAddress()) {
        return false;
    }

    if (addr.isMulticastAddress()) {
        return false;
    }

    if (!(addr instanceof Inet4Address)) {
        return false; // TODO add support for IPv6 - see SSHD-746
    }

    return !isLoopback(addr);

}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Get the server addresses from interfaces.
 *///  www.ja  v a 2 s  . co m
public static String getHostAddresses() {
    try {
        Enumeration interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        // Copy from enumeration to addresses vector, but filter loopback addresses
        ArrayList addresses = new ArrayList();
        while (interfaceEnumeration.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface) interfaceEnumeration.nextElement();
            // Remove loopback addresses
            Enumeration addressEnumeration = intf.getInetAddresses();
            while (addressEnumeration.hasMoreElements()) {
                InetAddress address = (InetAddress) addressEnumeration.nextElement();
                // Insert to addresses only if not loopback and not link local
                if ((!address.isLoopbackAddress()) && (!address.isLinkLocalAddress()))
                    addresses.add(address);
            }
        }
        // Pick one address from the remaining address space
        logger.debug("server available local addresses: " + addresses);
        // Now, multiple addresses are in the list, so copy all of them
        // into the result string.
        StringBuffer ips = new StringBuffer();
        for (int i = 0; i < addresses.size(); i++) {
            InetAddress address = (InetAddress) addresses.get(i);
            if (ips.length() > 0)
                ips.append(",");
            ips.append(address.getHostAddress());
        }
        return ips.toString();
    } catch (StoreException e) {
        throw e;
    } catch (Exception e) {
        throw new StoreException("exception while determining server address", e);
    }
}

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

private static String findOutgoingIpV6GivenAddress(String remoteIP) throws Exception {

    System.out.println("remoteIP: " + remoteIP);
    if (remoteIP.startsWith("[")) {
        remoteIP = remoteIP.substring(1, remoteIP.length() - 1);
        System.out.println("remoteIP: " + remoteIP);
    }/*from   w  w  w.j a  v a 2  s  . c o m*/

    if (System.getProperty("os.name").contains("Windows")) {
        NetworkInterface networkInterface;

        //if ipv6 then find the ipaddress of the network interface
        String line;
        short foundIfIndex = 0;
        final String COMMAND = "route print -6";
        List<RouteInfo> routes = new ArrayList<>();
        try {
            Process exec = Runtime.getRuntime().exec(COMMAND);
            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            //\s+addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$
            Pattern p = Pattern.compile("^\\s*(\\d+)\\s+(\\d+)\\s+(.*)\\s+(.*)$");
            while ((line = reader.readLine()) != null) {
                //do not check persistent routes. Only active routes
                if (line.startsWith("Persistent Routes")) {
                    break;
                }

                Matcher match = p.matcher(line);
                if (match.matches()) {
                    //                     System.out.println("line match: " + line);
                    String network = match.group(3).split("/")[0];
                    //String mask = match.group(2);
                    //String address = match.group(3);
                    short maskLength = Short.valueOf(match.group(3).split("/")[1].trim());

                    boolean networkMatch = ipv6InRange(network, maskLength, remoteIP);

                    if (networkMatch) {
                        short interfaceIndex = Short.valueOf(match.group(1));
                        short metric = Short.valueOf(match.group(2));
                        routes.add(new RouteInfo("", interfaceIndex, maskLength, metric));
                        System.out.println("added route: " + line);
                    }
                }
            }
            Collections.sort(routes);
            for (RouteInfo route : routes) {
            }

            if (!routes.isEmpty()) {
                foundIfIndex = routes.get(0).ifIndex;

                //based o nthe network interface index get the ip address
                networkInterface = NetworkInterface.getByIndex(foundIfIndex);

                Enumeration<InetAddress> test = networkInterface.getInetAddresses();

                while (test.hasMoreElements()) {
                    InetAddress inetaddress = test.nextElement();
                    if (inetaddress.isLinkLocalAddress()) {
                        continue;
                    } else {
                        if (inetaddress instanceof Inet6Address) {
                            System.out.println("interface host address: " + inetaddress.getHostAddress());
                            return "[" + inetaddress.getHostAddress() + "]";
                        } else
                            continue;
                    }
                }
            } else { //routes is Empty!
                System.out.println("No routable interface for remote IP");
                throw new Exception("No routable interface for remote IP");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    } else {

        List<RouteInfo> routes = new ArrayList<>();
        try {
            //ipv6 ^(.+)/(\d+)\s+(.+)\s(\d+)\s+(\d+)\s+(\d)\s+(.+)$
            //ipv4 ^\s+inet\s\addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$
            //linux route get command parsing: ipv4^.*via.*\s+dev\s+.*\s+src\s((?:[0-9\.]{1,3})+)
            //linux route get comand parsing: ipv6 ^.*\sfrom\s::\svia.*\sdev\s.*\ssrc\s((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)
            //new one ^.*\s+from\s+::\s+via.*\s+dev\s+.*\ssrc\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)\s+metric\s+\d+
            //final String COMMAND = "/sbin/ifconfig";
            final String COMMAND = "ip route get " + remoteIP;

            System.out.println("command = " + COMMAND);

            Process exec = Runtime.getRuntime().exec(COMMAND);
            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));

            System.out.println(System.getProperty("os.name"));
            String line;
            /* examples:
             * fdfd:55::98ac from :: via fdfd:55::98ac dev usb0  src fdfd:55::80fe  metric 0
            */
            Pattern p = Pattern.compile(
                    "^.*\\s+from\\s+::\\s+via.*\\sdev\\s+.*\\s+src\\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)\\s+metric\\s+\\d+.*");
            //String test = "fdfd:55::80ff from :: via fdfd:55::80ff dev usb0  src fdfd:55::80fe  metric 0";
            while ((line = reader.readLine()) != null) {
                System.out.println("result of command = " + line);
                Matcher match = p.matcher(line);
                if (match.matches()) {

                    String address = match.group(1);
                    System.out.println("match found. address = " + address);
                    routes.add(new RouteInfo(address, (short) 0, (short) 0, (short) 0));//metric is always 0, because we do not extract it from the ifconfig command.

                }
            }
            Collections.sort(routes);

            if (!routes.isEmpty())
                return routes.get(0).source;

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //^\s+inet6\s+addr:\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)/(\d{1,3})\s+\Scope:Global$
        //           NetworkInterface networkInterface;
        //         
        //         //if ipv6 then find the ipaddress of the network interface
        //          String line;
        //          short foundIfIndex = 0;
        //         final String COMMAND = "/sbin/ifconfig";
        //         List<RouteInfo> routes = new ArrayList<>();
        //         try {
        //            Process exec = Runtime.getRuntime().exec(COMMAND);
        //            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        //            //\s+addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$
        //            Pattern p = Pattern.compile("^\\s+inet6\\s+addr:\\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)/(\\d{1,3})\\s+\\Scope:Global$");
        //              while ((line = reader.readLine()) != null) {
        //                 //do not check persistent routes. Only active routes
        //                 if(line.startsWith("Persistent Routes")) {
        //                    break;
        //                 }
        //                 
        //                  Matcher match = p.matcher(line);
        //                  if (match.matches()) {
        //                      String network = match.group(1).trim();
        //                      short maskLength = Short.valueOf(match.group(2).trim());
        //                      
        //                      boolean networkMatch = ipv6InRange(network, maskLength, remoteIP);
        //                      
        //                      if (networkMatch) {
        //                         short interfaceIndex = Short.valueOf(match.group(1));
        //                          short metric = Short.valueOf(match.group(2));
        //                          routes.add(new RouteInfo("", interfaceIndex, maskLength, metric));
        //                          System.out.println("added route: " + line);
        //                      }
        //                  }
        //              }
        //              Collections.sort(routes);
        //              for (RouteInfo route : routes) {
        //              }
        //              
        //              if (!routes.isEmpty()) {
        //                 foundIfIndex = routes.get(0).ifIndex;
        //         
        //               //based o nthe network interface index get the ip address
        //               networkInterface = NetworkInterface.getByIndex(foundIfIndex);
        //            
        //               Enumeration<InetAddress> test = networkInterface.getInetAddresses();
        //               
        //               while (test.hasMoreElements()) {
        //                  InetAddress inetaddress = test.nextElement();
        //                  if (inetaddress.isLinkLocalAddress()) {
        //                     continue;
        //                  } else {
        //                     if (inetaddress instanceof Inet6Address) {
        //                        System.out.println("interface host address: " + inetaddress.getHostAddress());
        //                        return "[" + inetaddress.getHostAddress() + "]";
        //                     } else continue;
        //                  }
        //               }
        //              } else { //routes is Empty!
        //                 System.out.println("No routable interface for remote IP");
        //               throw new Exception("No routable interface for remote IP");
        //              }
        //         } catch (Exception ex) {
        //            ex.printStackTrace();
        //            throw ex;
        //         }

    }

    return null;
}

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

public static String IpType(InetAddress inetAddress) {
    try {//from   w  w  w . java 2 s .c  o  m
        final String ipVersion;
        if (inetAddress instanceof Inet4Address)
            ipVersion = "ipv4";
        else if (inetAddress instanceof Inet6Address)
            ipVersion = "ipv6";
        else
            ipVersion = "ipv?";

        if (inetAddress.isAnyLocalAddress())
            return "wildcard_" + ipVersion;
        if (inetAddress.isSiteLocalAddress())
            return "site_local_" + ipVersion;
        if (inetAddress.isLinkLocalAddress())
            return "link_local_" + ipVersion;
        if (inetAddress.isLoopbackAddress())
            return "loopback_" + ipVersion;
        return "public_" + ipVersion;

    } catch (final IllegalArgumentException e) {
        return "illegal_ip";
    }
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

public static List<InetAddress> getFilteredIPv6Addrs() {

    boolean ignoreLoopback = DhcpServerPolicies.globalPolicyAsBoolean(Property.DHCP_IGNORE_LOOPBACK);
    boolean ignoreLinkLocal = DhcpServerPolicies.globalPolicyAsBoolean(Property.DHCP_IGNORE_LINKLOCAL);

    List<InetAddress> myV6Addrs = new ArrayList<InetAddress>();
    List<InetAddress> allV6Addrs = getAllIPv6Addrs();
    if (allV6Addrs != null) {
        for (InetAddress ip : allV6Addrs) {
            if (ignoreLoopback && ip.isLoopbackAddress()) {
                log.debug("Skipping loopback address: " + ip);
                continue;
            }/*ww  w  .  jav a2s  . co m*/
            if (ignoreLinkLocal && ip.isLinkLocalAddress()) {
                log.debug("Skipping link local address: " + ip);
                continue;
            }
            myV6Addrs.add(ip);
        }
    }
    return myV6Addrs;
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

public static List<InetAddress> getFilteredIPv4Addrs() {

    boolean ignoreLoopback = DhcpServerPolicies.globalPolicyAsBoolean(Property.DHCP_IGNORE_LOOPBACK);
    boolean ignoreLinkLocal = DhcpServerPolicies.globalPolicyAsBoolean(Property.DHCP_IGNORE_LINKLOCAL);

    List<InetAddress> myV4Addrs = new ArrayList<InetAddress>();
    List<InetAddress> allV4Addrs = getAllIPv4Addrs();
    if (allV4Addrs != null) {
        for (InetAddress ip : allV4Addrs) {
            if (ignoreLoopback && ip.isLoopbackAddress()) {
                log.debug("Skipping loopback address: " + ip);
                continue;
            }//www.  ja  v  a2  s . c o m
            if (ignoreLinkLocal && ip.isLinkLocalAddress()) {
                log.debug("Skipping link local address: " + ip);
                continue;
            }
            myV4Addrs.add(ip);
        }
    }
    return myV4Addrs;
}

From source file:com.castlemock.web.basis.web.mvc.controller.AbstractController.java

/**
 * The method returns the local address (Not link local address, not loopback address) which the server is deployed on.
 * If the method does not find any INet4Address that is neither link local address and loopback address, the method
 * will return the the address 127.0.0.1
 * @return Returns the local address or 127.0.0.1 if no address was found
 * @throws SocketException Upon failing to extract network interfaces
 */// ww  w. j  a va  2 s . co m
public String getHostAddress() throws SocketException {
    if (endpointAddress != null && !endpointAddress.isEmpty()) {
        return endpointAddress;
    }

    final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfaces.nextElement();
        final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            final InetAddress address = addresses.nextElement();
            if (!address.isLinkLocalAddress() && !address.isLoopbackAddress()
                    && address instanceof Inet4Address) {
                return address.getHostAddress();
            }
        }
    }

    return LOCAL_ADDRESS;
}

From source file:org.apache.carbondata.core.dictionary.service.AbstractDictionaryServer.java

public String findLocalIpAddress(Logger LOGGER) {
    try {// w w w . j  ava 2s.c o  m
        String defaultIpOverride = System.getenv("SPARK_LOCAL_IP");
        if (defaultIpOverride != null) {
            return defaultIpOverride;
        } else {
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                // Address resolves to something like 127.0.1.1, which happens on Debian; try to find
                // a better address using the local network interfaces
                // getNetworkInterfaces returns ifs in reverse order compared to ifconfig output order
                // on unix-like system. On windows, it returns in index order.
                // It's more proper to pick ip address following system output order.
                Enumeration<NetworkInterface> activeNetworkIFs = NetworkInterface.getNetworkInterfaces();
                List<NetworkInterface> reOrderedNetworkIFs = new ArrayList<NetworkInterface>();
                while (activeNetworkIFs.hasMoreElements()) {
                    reOrderedNetworkIFs.add(activeNetworkIFs.nextElement());
                }

                if (!SystemUtils.IS_OS_WINDOWS) {
                    Collections.reverse(reOrderedNetworkIFs);
                }

                for (NetworkInterface ni : reOrderedNetworkIFs) {
                    Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress addr = inetAddresses.nextElement();
                        if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
                                && addr instanceof Inet4Address) {
                            // We've found an address that looks reasonable!
                            LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                                    + " resolves to a loopback address: " + address.getHostAddress()
                                    + "; using " + addr.getHostAddress() + " instead (on interface "
                                    + ni.getName() + ")");
                            LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                            return addr.getHostAddress();
                        }
                    }
                    LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                            + " resolves to a loopback address: " + address.getHostAddress()
                            + ", but we couldn't find any external IP address!");
                    LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                }
            }
            return address.getHostAddress();
        }
    } catch (UnknownHostException e) {
        LOGGER.error("do not get local host address:" + e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (SocketException e) {
        LOGGER.error("do not get net work interface:" + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.doxu.g2.gwc.crawler.CrawlThread.java

private boolean isAddressBlocked(InetAddress ip) {
    return ip.isLinkLocalAddress() || ip.isLoopbackAddress() || ip.isSiteLocalAddress()
            || ip.isMulticastAddress();/*from w w  w  .ja va2s  . c  o  m*/
}

From source file:org.apache.hadoop.hbase.regionserver.TestRegionServerHostname.java

@Test(timeout = 120000)
public void testRegionServerHostname() throws Exception {
    final int NUM_MASTERS = 1;
    final int NUM_RS = 1;
    Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces();

    while (netInterfaceList.hasMoreElements()) {
        NetworkInterface ni = netInterfaceList.nextElement();
        Enumeration<InetAddress> addrList = ni.getInetAddresses();
        // iterate through host addresses and use each as hostname
        while (addrList.hasMoreElements()) {
            InetAddress addr = addrList.nextElement();
            if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) {
                continue;
            }//  w w  w  . j  a  v  a2s.co  m
            String hostName = addr.getHostName();
            LOG.info("Found " + hostName + " on " + ni);

            TEST_UTIL.getConfiguration().set(HRegionServer.MASTER_HOSTNAME_KEY, hostName);
            TEST_UTIL.getConfiguration().set(HRegionServer.RS_HOSTNAME_KEY, hostName);
            TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS);
            try {
                ZooKeeperWatcher zkw = TEST_UTIL.getZooKeeperWatcher();
                List<String> servers = ZKUtil.listChildrenNoWatch(zkw, zkw.rsZNode);
                // there would be NUM_RS+1 children - one for the master
                assertTrue(servers.size() == NUM_RS + 1);
                for (String server : servers) {
                    assertTrue("From zookeeper: " + server + " hostname: " + hostName,
                            server.startsWith(hostName.toLowerCase() + ","));
                }
                zkw.close();
            } finally {
                TEST_UTIL.shutdownMiniCluster();
            }
        }
    }
}