Example usage for java.net NetworkInterface getByIndex

List of usage examples for java.net NetworkInterface getByIndex

Introduction

In this page you can find the example usage for java.net NetworkInterface getByIndex.

Prototype

public static NetworkInterface getByIndex(int index) throws SocketException 

Source Link

Document

Get a network interface given its index.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    InetAddress address = InetAddress.getByName("web.mit.edu");
    System.out.println("Name: " + address.getHostName());
    System.out.println("Addr: " + address.getHostAddress());
    System.out.println("Reach: " + address.isReachable(NetworkInterface.getByIndex(0), 0, 3000));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);// w w w .  j a va2 s  .  c  o m
    }
    ms.leaveGroup(InetAddress.getByName("google.com"));

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);/*from  w w w .j  a  v  a 2  s .  c o m*/
    }
    ms.setLoopbackMode(true);

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//from  ww  w .j ava2 s.co m
    }
    ms.setNetworkInterface(NetworkInterface.getByIndex(0));

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//  ww w  .  j av  a  2s  .c o m
    }
    ms.setTimeToLive(1000);

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);/*  w  ww . ja  v  a  2s . c  o m*/
    }
    ms.leaveGroup(InetSocketAddress.createUnresolved("java2s.com", 8080), NetworkInterface.getByIndex(0));

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);/*from  ww  w  .java  2s  . co  m*/
    }
    ms.setInterface(InetAddress.getByName("google.com"));

    ms.close();
}

From source file:ch.cyberduck.core.socket.NetworkInterfaceAwareSocketFactory.java

private NetworkInterface findIPv6Interface(Inet6Address address) throws IOException {
    if (blacklisted.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Ignore IP6 default network interface setup with empty blacklist");
        }/*from ww w .j  a  v a 2 s. c  o m*/
        return null;
    }
    if (address.getScopeId() != 0) {
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "Ignore IP6 default network interface setup for address with scope identifier %d",
                    address.getScopeId()));
        }
        return null;
    }
    // If we find an interface name en0 that supports IPv6 make it the default.
    // We must use the index of the network interface. Referencing the interface by name will still
    // set the scope id to '0' referencing the awdl0 interface that is first in the list of enumerated
    // network interfaces instead of its correct index in <code>java.net.Inet6Address</code>
    // Use private API to defer the numeric format for the address
    List<Integer> indexes = new ArrayList<Integer>();
    final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
    while (enumeration.hasMoreElements()) {
        indexes.add(enumeration.nextElement().getIndex());
    }
    for (Integer index : indexes) {
        final NetworkInterface n = NetworkInterface.getByIndex(index);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Evaluate interface with %s index %d", n, index));
        }
        if (!n.isUp()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Ignore interface %s not up", n));
            }
            continue;
        }
        if (blacklisted.contains(n.getName())) {
            log.warn(String.format("Ignore network interface %s disabled with blacklist", n));
            continue;
        }
        for (InterfaceAddress i : n.getInterfaceAddresses()) {
            if (i.getAddress() instanceof Inet6Address) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Selected network interface %s", n));
                }
                return n;
            }
        }
        log.warn(String.format("No IPv6 for interface %s", n));
    }
    log.warn("No network interface found for IPv6");
    return null;
}

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);
    }// w ww. ja v  a2s  . 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:com.chiralBehaviors.autoconfigure.AutoConfigure.java

/**
 * @return the network interface to bind this interface to.
 *///  w ww .  j  a va2 s  .  co m
protected NetworkInterface determineNetworkInterface() {
    NetworkInterface iface;
    if (config.networkInterface == null) {
        try {
            iface = NetworkInterface.getByIndex(1);
        } catch (SocketException e) {
            String msg = String.format("Unable to obtain default network interface");
            logger.error(msg, e);
            throw new IllegalStateException(msg, e);
        }
    } else {
        try {
            iface = NetworkInterface.getByName(config.networkInterface);
        } catch (SocketException e) {
            String msg = String.format("Unable to obtain network interface[%s]", config.networkInterface);
            logger.error(msg, e);
            throw new IllegalStateException(msg, e);
        }
        if (iface == null) {
            String msg = String.format("Unable to find network interface [%s]", config.networkInterface);
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
    }
    try {
        if (!iface.isUp()) {
            String msg = String.format("Network interface [%s] is not up!", iface.getName());
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
    } catch (SocketException e) {
        String msg = String.format("Unable to determine if network interface [%s] is up", iface.getName());
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
    logger.info(String.format("Network interface [%s] is up", iface.getDisplayName()));
    return iface;
}