Esempio n. 1
0
  public static String[] getLocalCidrs() {
    String defaultHostIp = getDefaultHostIp();

    List<String> cidrList = new ArrayList<String>();
    try {
      for (NetworkInterface ifc :
          IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
        if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
          for (InterfaceAddress address : ifc.getInterfaceAddresses()) {
            InetAddress addr = address.getAddress();
            int prefixLength = address.getNetworkPrefixLength();
            if (prefixLength < 32 && prefixLength > 0) {
              String ip = ipFromInetAddress(addr);
              if (ip.equalsIgnoreCase(defaultHostIp))
                cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
            }
          }
        }
      }
    } catch (SocketException e) {
      s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }

    return cidrList.toArray(new String[0]);
  }
Esempio n. 2
0
  // on linux system
  public void init2() {
    try {
      NetworkInterface networkInterface = NetworkInterface.getByName("eth0");
      Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
      while (inetAddresses.hasMoreElements()) {
        InetAddress address = inetAddresses.nextElement();
        if (!address.isLinkLocalAddress()) { // just get IPv4 address
          localAddress = address;
        }
      }
      // get broadcast address
      List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
      for (InterfaceAddress address : addresses) {
        if (address.getBroadcast() != null) {
          broadcastAddress = address.getBroadcast();
          break;
        }
      }
      if (broadcastAddress == null) {
        System.out.println("get broadcast address error!");
      }
      System.out.println("local ip address is " + localAddress.getHostAddress());
      System.out.println("broadcast address is " + broadcastAddress.getHostAddress());

      socket = new DatagramSocket();
      socket.setBroadcast(true);
    } catch (SocketException se) {
      se.printStackTrace();
    }
  }
Esempio n. 3
0
  public void init() {
    try {
      localAddress = InetAddress.getLocalHost();
      if (localAddress.isLoopbackAddress()) {
        System.out.println("get local ip error!");
        return;
      }
      NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);
      List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
      for (InterfaceAddress address : addresses) {
        if (address.getAddress() instanceof Inet6Address) {
          continue;
        }
        if (address.getBroadcast() != null) {
          broadcastAddress = address.getBroadcast();
          break;
        } else {
          System.out.println("get broadcast address error!");
        }
      }
      System.out.println("local ip address is " + localAddress.getHostAddress());
      System.out.println("broadcast address is " + broadcastAddress.getHostAddress());

      socket = new DatagramSocket(2000);
      socket.setBroadcast(true);

    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (SocketException se) {
      se.printStackTrace();
    }
  }
Esempio n. 4
0
  private static void displayInterfaceInformation(final NetworkInterface networkInterface)
      throws SocketException {
    LOG.trace(MessageFormat.format("Display name: %s%n", networkInterface.getDisplayName()));
    LOG.trace(MessageFormat.format("Name: %s%n", networkInterface.getName()));
    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
    for (InetAddress inetAddress : Collections.list(inetAddresses)) {
      LOG.trace(MessageFormat.format("InetAddress: %s%n", inetAddress));
    }

    LOG.trace(MessageFormat.format("Parent: %s%n", networkInterface.getParent()));
    LOG.trace(MessageFormat.format("Up? %s%n", networkInterface.isUp()));
    LOG.trace(MessageFormat.format("Loopback? %s%n", networkInterface.isLoopback()));
    LOG.trace(MessageFormat.format("PointToPoint? %s%n", networkInterface.isPointToPoint()));
    LOG.trace(MessageFormat.format("Supports multicast? %s%n", networkInterface.isVirtual()));
    LOG.trace(MessageFormat.format("Virtual? %s%n", networkInterface.isVirtual()));
    LOG.trace(
        MessageFormat.format(
            "Hardware address: %s%n", Arrays.toString(networkInterface.getHardwareAddress())));
    LOG.trace(MessageFormat.format("MTU: %s%n", networkInterface.getMTU()));

    List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
    for (InterfaceAddress addr : interfaceAddresses) {
      LOG.trace(MessageFormat.format("InterfaceAddress: %s%n", addr.getAddress()));
    }
    LOG.trace(MessageFormat.format("%n", null));
    Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
    for (NetworkInterface aNetworkInterface : Collections.list(subInterfaces)) {
      LOG.trace(MessageFormat.format("%nSubInterface%n", null));
      displayInterfaceInformation(aNetworkInterface);
    }
    LOG.trace(MessageFormat.format("%n", null));
  }
Esempio n. 5
0
  public static String[] getNetworkParams(NetworkInterface nic) {
    List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
      return null;
    }
    InterfaceAddress addr = null;
    for (InterfaceAddress iaddr : addrs) {
      InetAddress inet = iaddr.getAddress();
      if (!inet.isLinkLocalAddress()
          && !inet.isLoopbackAddress()
          && !inet.isMulticastAddress()
          && inet.getAddress().length == 4) {
        addr = iaddr;
        break;
      }
    }
    if (addr == null) {
      return null;
    }
    String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
      byte[] mac = nic.getHardwareAddress();
      result[1] = byte2Mac(mac);
    } catch (Exception e) {
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
  }
Esempio n. 6
0
  static {
    try {

      InetAddress addr = InetAddress.getLocalHost();
      HOST_NAME = addr.getHostName();
      Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
      for (NetworkInterface netint : Collections.list(nets)) {
        if (null != netint.getHardwareAddress()) {
          List<InterfaceAddress> list = netint.getInterfaceAddresses();
          for (InterfaceAddress interfaceAddress : list) {
            InetAddress ip = interfaceAddress.getAddress();
            if (ip instanceof Inet4Address) {
              HOST_IP += interfaceAddress.getAddress().toString();
            }
          }
        }
      }
      HOST_IP = HOST_IP.replaceAll("null", "");
    } catch (Exception e) {
      System.out.println("获取服务器IP出错");
    }

    try {
      osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

      TotalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    } catch (Exception e) {
      System.out.println("获取系统信息失败");
      e.printStackTrace();
    }
  }
Esempio n. 7
0
 private InetAddress getLocalAddress(String adaptorName) {
   try {
     Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
     while (b.hasMoreElements()) {
       NetworkInterface networkInterface = b.nextElement();
       if (networkInterface.getName().equals(adaptorName)) {
         for (InterfaceAddress f : networkInterface.getInterfaceAddresses()) {
           if (f.getAddress().isSiteLocalAddress()) {
             return f.getAddress();
           }
         }
       }
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
   return null;
 }
  public static InetAddress getBroadcast() {
    InetAddress found_bcast_address = null;
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
      Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
      while (niEnum.hasMoreElements()) {
        NetworkInterface ni = niEnum.nextElement();
        if (!ni.isLoopback()) {
          for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
            found_bcast_address = interfaceAddress.getBroadcast();
          }
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }

    return found_bcast_address;
  }
Esempio n. 9
0
 public static String getBroadcast() {
   if (IP.broadcast == null) {
     try {
       NetworkInterface network = NetworkInterface.getByInetAddress(Inet4Address.getLocalHost());
       InterfaceAddress address = null;
       for (InterfaceAddress add : network.getInterfaceAddresses()) {
         if (add != null) {
           address = add;
           break;
         }
       }
       IP.broadcast = address.getBroadcast().toString().split("/")[1];
       IP.mask = IP.parsePrefix(address.getNetworkPrefixLength());
     } catch (SocketException | UnknownHostException e) {
       Core.exception(e, "Cannot create Broadcast", "IP");
     }
   }
   return IP.broadcast;
 }
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void populateLanMasks(Context context, String[] names, InterfaceDetails ret) {
      try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

        while (en.hasMoreElements()) {
          NetworkInterface intf = en.nextElement();
          boolean match = false;

          if (!intf.isUp() || intf.isLoopback()) {
            continue;
          }

          for (String pattern : ITFS_WIFI) {
            if (intf.getName().startsWith(truncAfter(pattern, "\\+"))) {
              match = true;
              break;
            }
          }
          if (!match) continue;
          ret.wifiName = intf.getName();

          Iterator<InterfaceAddress> addrList = intf.getInterfaceAddresses().iterator();
          while (addrList.hasNext()) {
            InterfaceAddress addr = addrList.next();
            InetAddress ip = addr.getAddress();
            String mask =
                truncAfter(ip.getHostAddress(), "%") + "/" + addr.getNetworkPrefixLength();

            if (ip instanceof Inet4Address) {
              ret.lanMaskV4 = mask;
            } else if (ip instanceof Inet6Address) {
              ret.lanMaskV6 = mask;
            }
          }
        }
      } catch (SocketException e) {
        Log.e(TAG, "Error fetching network interface list");
      } catch (Exception e) {
        Log.e(TAG, "Error fetching network interface list");
      }
    }
  public static List<InetAddress> getLocalAddresses() {
    List<InetAddress> addresses = Lists.newArrayList();
    Enumeration<NetworkInterface> networkInterfaces;
    try {
      networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      throw new IllegalStateException("Error reading network addresses", e);
    }

    while (networkInterfaces.hasMoreElements()) {
      NetworkInterface networkInterface = networkInterfaces.nextElement();
      List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
      for (InterfaceAddress interfaceAddress : interfaceAddresses) {
        InetAddress address = interfaceAddress.getAddress();
        addresses.add(address);
      }
    }

    return addresses;
  }
Esempio n. 12
0
  private boolean isOnSubnet(InterfaceAddress receiver, InetAddress sender) {
    byte[] receiverBytes = receiver.getAddress().getAddress();
    byte[] senderBytes = sender.getAddress();
    byte[] subnetBytes = new byte[4];
    short length = receiver.getNetworkPrefixLength();
    int position = 0;

    if (length < 8) {
      subnetBytes[0] = 0;
      subnetBytes[1] = 0;
      subnetBytes[2] = 0;
      subnetBytes[3] = (byte) (Math.pow(2, length) / 2);
    } else if (length < 16) {
      subnetBytes[0] = 0;
      subnetBytes[1] = 0;
      subnetBytes[2] = (byte) (Math.pow(2, length) / 2);
      subnetBytes[3] = 127;
    } else if (length < 24) {
      subnetBytes[0] = 0;
      subnetBytes[1] = (byte) (Math.pow(2, length) / 2);
      subnetBytes[2] = 127;
      subnetBytes[3] = 127;
    } else {
      subnetBytes[0] = (byte) (Math.pow(2, length) / 2);
      subnetBytes[1] = 127;
      subnetBytes[2] = 127;
      subnetBytes[3] = 127;
    }

    for (int x = senderBytes.length - 1; x >= 0; x--) {
      if ((senderBytes[x] & subnetBytes[x]) != (receiverBytes[x] & subnetBytes[x])) {
        return false;
      }

      position++;
    }

    return true;
  }
Esempio n. 13
0
  public static void printParameter(NetworkInterface ni) throws SocketException {
    System.out.println(" Name = " + ni.getName());
    System.out.println(" Display Name = " + ni.getDisplayName());
    System.out.println(" Is up = " + ni.isUp());
    System.out.println(" Support multicast = " + ni.supportsMulticast());
    System.out.println(" Is loopback = " + ni.isLoopback());
    System.out.println(" Is virtual = " + ni.isVirtual());
    System.out.println(" Is point to point = " + ni.isPointToPoint());
    System.out.println(" Hardware address = " + ni.getHardwareAddress());
    System.out.println(" MTU = " + ni.getMTU());

    System.out.println("\nList of Interface Addresses:");
    List<InterfaceAddress> list = ni.getInterfaceAddresses();
    Iterator<InterfaceAddress> it = list.iterator();

    while (it.hasNext()) {
      InterfaceAddress ia = it.next();
      System.out.println(" Address = " + ia.getAddress());
      System.out.println(" Broadcast = " + ia.getBroadcast());
      System.out.println(" Network prefix length = " + ia.getNetworkPrefixLength());
      System.out.println("");
    }
  }
Esempio n. 14
0
  public ArrayList<InetAddress> ping() {
    ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
    // Find the server using UDP broadcast
    try {
      // Open a random port to send the package
      DatagramSocket c = new DatagramSocket();
      c.setBroadcast(true);

      byte[] sendData = "DISCOVER_FUIFSERVER_REQUEST".getBytes();

      // Try the 255.255.255.255 first
      try {
        log.info("client >>> sending request packet to: 255.255.255.255:8888 (DEFAULT)");
        DatagramPacket sendPacket =
            new DatagramPacket(
                sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888);
        c.send(sendPacket);
        byte[] recvBuf = new byte[15000];
        DatagramPacket pong = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(pong);
        log.info("client >>> recieved PONG");
      } catch (Exception e) {
      }

      // Broadcast the message over all the network interfaces
      Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
          continue; // Don't want to broadcast to the loopback
          // interface
        }

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress broadcast = interfaceAddress.getBroadcast();
          if (broadcast == null) {
            continue;
          }

          // Send the broadcast package!
          try {
            log.info("client >>> sending request packet to: 255.255.255.255:8888 (DEFAULT)");
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, broadcast, 8888);
            c.send(sendPacket);
          } catch (Exception e) {
          }

          log.info(
              "client >>> Request packet sent to: "
                  + broadcast.getHostAddress()
                  + "; Interface: "
                  + networkInterface.getDisplayName());
        }
      }

      log.info(">>> Done looping over all network interfaces. Now waiting for a reply!");

      // Wait for a response
      byte[] recvBuf = new byte[15000];
      DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
      c.receive(receivePacket);

      // We have a response
      log.info(
          ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

      // Check if the message is correct
      String message = new String(receivePacket.getData()).trim();
      if (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) {
        // DO SOMETHING WITH THE SERVER'S IP (for example, store it in
        // your controller)
        // Controller_Base.setServerIp(receivePacket.getAddress());
        ret.add(receivePacket.getAddress());
      }

      // Close the port!
      c.close();
    } catch (IOException e) {
      Logging.logException(e);
    }

    return ret;
  }
  public List<MsgEvent> discover() {
    List<MsgEvent> discoveryList = null;
    // Find the server using UDP broadcast
    try {
      discoveryList = new ArrayList<MsgEvent>();
      // Open a random port to send the package
      c = new DatagramSocket();
      c.setBroadcast(true);

      byte[] sendData = "DISCOVER_FUIFSERVER_REQUEST".getBytes();

      // Try the 255.255.255.255 first
      try {
        DatagramPacket sendPacket =
            new DatagramPacket(
                sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 32005);
        c.send(sendPacket);
        // System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255
        // (DEFAULT)");
      } catch (Exception e) {
      }

      // Broadcast the message over all the network interfaces
      Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
          continue; // Don't want to broadcast to the loopback interface
        }

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress broadcast = interfaceAddress.getBroadcast();
          if (broadcast == null) {
            continue;
          }

          // Send the broadcast package!
          try {
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, broadcast, 32005);
            c.send(sendPacket);
          } catch (Exception e) {
          }

          // System.out.println(getClass().getName() + ">>> Request packet sent to: " +
          // broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
        }
      }

      // System.out.println(getClass().getName() + ">>> Done looping over all network interfaces.
      // Now waiting for a reply!");

      // Wait for a response
      while (!c.isClosed()) {
        try {
          byte[] recvBuf = new byte[15000];
          DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
          c.receive(receivePacket);

          // We have a response
          // System.out.println(getClass().getName() + ">>> Broadcast response from server: " +
          // receivePacket.getAddress().getHostAddress());

          // Check if the message is correct
          // System.out.println(new String(receivePacket.getData()));

          String json = new String(receivePacket.getData()).trim();
          // String response = "region=region0,agent=agent0,recaddr=" +
          // packet.getAddress().getHostAddress();
          try {
            MsgEvent me = gson.fromJson(json, MsgEvent.class);
            if (me != null) {
              if (!me.getParam("clientip").equals(receivePacket.getAddress().getHostAddress())) {
                // System.out.println("SAME HOST");
                // System.out.println(me.getParamsString() +
                // receivePacket.getAddress().getHostAddress());
                me.setParam("serverip", receivePacket.getAddress().getHostAddress());
                discoveryList.add(me);
              }
            }
          } catch (Exception ex) {
            System.out.println("in loop 0" + ex.toString());
          }
        } catch (SocketException ex) {
          // eat message.. this should happen
        } catch (Exception ex) {
          System.out.println("in loop 1" + ex.toString());
        }
      }
      // Close the port!
      // c.close();
      // System.out.println("CODY : Dicsicer Client Worker Engned!");
    } catch (Exception ex) {
      System.out.println("while not closed: " + ex.toString());
    }
    return discoveryList;
  }
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public List<NetInterface<? extends NetInterfaceAddress>> getActiveNetworkInterfaces()
      throws KuraException {
    IPAddress netAddress = null;
    NetInterfaceAddressImpl addressImpl = null;
    List<NetInterfaceAddress> addresses = null;
    List<NetInterface<? extends NetInterfaceAddress>> interfaces =
        new ArrayList<NetInterface<? extends NetInterfaceAddress>>();

    EthernetInterfaceImpl ethInterface = null;
    java.net.NetworkInterface jnInterface = null;
    List<java.net.InterfaceAddress> jnInterfaceAddresses = null;
    Enumeration<java.net.NetworkInterface> jnInterfaces = null;
    try {
      jnInterfaces = java.net.NetworkInterface.getNetworkInterfaces();
      while (jnInterfaces.hasMoreElements()) {

        try {
          jnInterface = jnInterfaces.nextElement();
          if (jnInterface.isUp()
              && !jnInterface.isVirtual()
              && !jnInterface.isLoopback()
              && !jnInterface.isPointToPoint()
              && (jnInterface.getHardwareAddress() != null)
              && !jnInterface.getInterfaceAddresses().isEmpty()) {

            ethInterface = new EthernetInterfaceImpl(jnInterface.getName());
            ethInterface.setVirtual(jnInterface.isVirtual());
            ethInterface.setState(NetInterfaceState.ACTIVATED);
            ethInterface.setAutoConnect(true);

            byte[] hwAddr = null;
            boolean isUp = false;
            boolean isLoop = false;
            int mtu = 0;
            boolean isP2p = false;
            boolean multi = false;
            try {
              hwAddr = jnInterface.getHardwareAddress();
              isUp = jnInterface.isUp();
              isLoop = jnInterface.isLoopback();
              mtu = jnInterface.getMTU();
              isP2p = jnInterface.isPointToPoint();
              multi = jnInterface.supportsMulticast();
            } catch (Exception e) {
              s_logger.warn(
                  "Exception while getting information for interface " + jnInterface.getName(), e);
            }
            ethInterface.setHardwareAddress(hwAddr);
            ethInterface.setLinkUp(isUp);
            ethInterface.setLoopback(isLoop);
            ethInterface.setMTU(mtu);
            ethInterface.setPointToPoint(isP2p);
            ethInterface.setSupportsMulticast(multi);
            ethInterface.setUp(isUp);

            addresses = new ArrayList<NetInterfaceAddress>();
            jnInterfaceAddresses = jnInterface.getInterfaceAddresses();
            for (java.net.InterfaceAddress jnInterfaceAddress : jnInterfaceAddresses) {

              netAddress = IPAddress.getByAddress(jnInterfaceAddress.getAddress().getAddress());
              addressImpl = new NetInterfaceAddressImpl();
              addressImpl.setAddress(netAddress);
              if (jnInterfaceAddress.getBroadcast() != null) {
                addressImpl.setBroadcast(
                    IPAddress.getByAddress(jnInterfaceAddress.getBroadcast().getAddress()));
              }
              addressImpl.setNetworkPrefixLength(jnInterfaceAddress.getNetworkPrefixLength());

              addresses.add(addressImpl);
            }
            ethInterface.setNetInterfaceAddresses(addresses);
            interfaces.add(ethInterface);
          }
        } catch (SocketException se) {
          s_logger.warn(
              "Exception while getting information for interface " + jnInterface.getName(), se);
        }
      }
    } catch (Exception e) {
      throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    }
    return interfaces;
  }
  public void start() {
    try {

      lock.lock();

      logger.debug("Starting LIFX communication handler for bulb '{}'.", macAsHex);

      if (networkJob == null || networkJob.isCancelled()) {
        networkJob =
            scheduler.scheduleWithFixedDelay(
                networkRunnable, 0, PACKET_INTERVAL, TimeUnit.MILLISECONDS);
      }

      source = UUID.randomUUID().getLeastSignificantBits() & (-1L >>> 32);
      logger.debug(
          "The LIFX handler will use '{}' as source identifier", Long.toString(source, 16));
      broadcastAddresses = new ArrayList<InetSocketAddress>();
      interfaceAddresses = new ArrayList<InetAddress>();

      Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
      while (networkInterfaces.hasMoreElements()) {
        NetworkInterface iface = networkInterfaces.nextElement();
        if (iface.isUp() && !iface.isLoopback()) {
          for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) {
            if (ifaceAddr.getAddress() instanceof Inet4Address) {
              logger.debug(
                  "Adding '{}' as interface address with MTU {}",
                  ifaceAddr.getAddress(),
                  iface.getMTU());
              if (iface.getMTU() > bufferSize) {
                bufferSize = iface.getMTU();
              }
              interfaceAddresses.add(ifaceAddr.getAddress());
              if (ifaceAddr.getBroadcast() != null) {
                logger.debug("Adding '{}' as broadcast address", ifaceAddr.getBroadcast());
                broadcastAddresses.add(
                    new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT));
              }
            }
          }
        }
      }

      selector = Selector.open();

      DatagramChannel broadcastChannel =
          DatagramChannel.open(StandardProtocolFamily.INET)
              .setOption(StandardSocketOptions.SO_REUSEADDR, true)
              .setOption(StandardSocketOptions.SO_BROADCAST, true);
      broadcastChannel.configureBlocking(false);

      int offset = lightCounter.getAndIncrement();
      logger.debug("Binding the broadcast channel on port {}", BROADCAST_PORT + offset);
      broadcastChannel.bind(new InetSocketAddress(BROADCAST_PORT + offset));

      broadcastKey =
          broadcastChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

      currentLightState.setOffline();

      // look for lights on the network
      GetServiceRequest packet = new GetServiceRequest();
      broadcastPacket(packet);

    } catch (Exception ex) {
      logger.error("Error occured while initializing LIFX handler: " + ex.getMessage(), ex);
    } finally {
      lock.unlock();
    }
  }
 /**
  * Discover WS device on the local network
  *
  * @return list of unique devices access strings which might be URLs in most cases
  */
 public static Collection<String> discoverWsDevices() {
   final Collection<String> addresses = new ConcurrentSkipListSet<>();
   final CountDownLatch serverStarted = new CountDownLatch(1);
   final CountDownLatch serverFinished = new CountDownLatch(1);
   final Collection<InetAddress> addressList = new ArrayList<>();
   try {
     final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
     if (interfaces != null) {
       while (interfaces.hasMoreElements()) {
         NetworkInterface anInterface = interfaces.nextElement();
         if (!anInterface.isLoopback()) {
           final List<InterfaceAddress> interfaceAddresses = anInterface.getInterfaceAddresses();
           for (InterfaceAddress address : interfaceAddresses) {
             addressList.add(address.getAddress());
           }
         }
       }
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
   ExecutorService executorService = Executors.newCachedThreadPool();
   for (final InetAddress address : addressList) {
     Runnable runnable =
         new Runnable() {
           public void run() {
             try {
               final String uuid = UUID.randomUUID().toString();
               final String probe =
                   WS_DISCOVERY_PROBE_MESSAGE.replaceAll(
                       "<wsa:MessageID>urn:uuid:.*</wsa:MessageID>",
                       "<wsa:MessageID>urn:uuid:" + uuid + "</wsa:MessageID>");
               final int port = random.nextInt(20000) + 40000;
               @SuppressWarnings("SocketOpenedButNotSafelyClosed")
               final DatagramSocket server = new DatagramSocket(port, address);
               new Thread() {
                 public void run() {
                   try {
                     final DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
                     server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
                     long timerStarted = System.currentTimeMillis();
                     while (System.currentTimeMillis() - timerStarted < (WS_DISCOVERY_TIMEOUT)) {
                       serverStarted.countDown();
                       server.receive(packet);
                       final Collection<String> collection =
                           parseSoapResponseForUrls(
                               Arrays.copyOf(packet.getData(), packet.getLength()));
                       for (String key : collection) {
                         addresses.add(key);
                       }
                     }
                   } catch (SocketTimeoutException ignored) {
                   } catch (Exception e) {
                     e.printStackTrace();
                   } finally {
                     serverFinished.countDown();
                     server.close();
                   }
                 }
               }.start();
               try {
                 serverStarted.await(1000, TimeUnit.MILLISECONDS);
               } catch (InterruptedException e) {
                 e.printStackTrace();
               }
               if (address instanceof Inet4Address) {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4),
                         WS_DISCOVERY_PORT));
               } else {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6),
                         WS_DISCOVERY_PORT));
               }
             } catch (Exception e) {
               e.printStackTrace();
             }
             try {
               serverFinished.await((WS_DISCOVERY_TIMEOUT), TimeUnit.MILLISECONDS);
             } catch (InterruptedException e) {
               e.printStackTrace();
             }
           }
         };
     executorService.submit(runnable);
   }
   try {
     executorService.shutdown();
     executorService.awaitTermination(WS_DISCOVERY_TIMEOUT + 2000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ignored) {
   }
   return addresses;
 }
Esempio n. 19
0
  /**
   * Automatic UDP discovery of a MAX!Cube
   *
   * @return if the cube is found, returns the IP address as a string. Otherwise returns null
   */
  public static final String discoverIp() {

    String maxCubeIP = null;
    String maxCubeName = null;
    String rfAddress = null;

    Logger logger = LoggerFactory.getLogger(MaxCubeDiscover.class);

    // Find the MaxCube using UDP broadcast
    try {
      DatagramSocket bcSend = new DatagramSocket();
      bcSend.setBroadcast(true);

      byte[] sendData = "eQ3Max*\0**********I".getBytes();

      // Broadcast the message over all the network interfaces
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
          continue;
        }

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress broadcast = interfaceAddress.getBroadcast();
          if (broadcast == null) {
            continue;
          }

          // Send the broadcast package!
          try {
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, broadcast, 23272);
            bcSend.send(sendPacket);
          } catch (Exception e) {
            logger.debug(e.getMessage());
            logger.debug(Utils.getStackTrace(e));
          }

          logger.trace(
              "Request packet sent to: {} Interface: {}",
              broadcast.getHostAddress(),
              networkInterface.getDisplayName());
        }
      }

      logger.trace("Done looping over all network interfaces. Now waiting for a reply!");
      bcSend.close();

      DatagramSocket bcReceipt = new DatagramSocket(23272);
      bcReceipt.setReuseAddress(true);

      // Wait for a response
      byte[] recvBuf = new byte[15000];
      DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
      bcReceipt.receive(receivePacket);

      // We have a response
      logger.trace("Broadcast response from server: {}", receivePacket.getAddress());

      // Check if the message is correct
      String message = new String(receivePacket.getData()).trim();

      if (message.startsWith("eQ3Max")) {

        maxCubeIP = receivePacket.getAddress().getHostAddress();
        maxCubeName = message.substring(0, 8);
        rfAddress = message.substring(8, 18);
        logger.debug("Found at: {}", maxCubeIP);
        logger.debug("Name    : {}", maxCubeName);
        logger.debug("Serial  : {}", rfAddress);
        logger.trace("Message : {}", message);
      } else {
        logger.info("No Max!Cube gateway found on network");
      }

      // Close the port!
      bcReceipt.close();

    } catch (IOException ex) {
      logger.debug(ex.toString());
    }
    return maxCubeIP;
  }
Esempio n. 20
0
  @Override
  public void run() {
    long id = System.currentTimeMillis();
    running = true;

    log.info("Beacon thread starting");

    long lastBeacon = System.currentTimeMillis() - BEACON_GAP;
    while (running) {
      while (running && (System.currentTimeMillis() - lastBeacon) < BEACON_GAP) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
      }
      if (!running) continue;

      DatagramSocket socket = null;
      try {
        CentralBeacon beaconPackage =
            CentralBeacon.newBuilder()
                .setServerVersion(Central.VERSION)
                .setSensorPort(deviceServer.getPort())
                .setApiPort(apiServer.getPort())
                .setServerId(id)
                .build();
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        beaconPackage.writeDelimitedTo(data);

        socket = new DatagramSocket();
        socket.setBroadcast(true);

        List<InetAddress> broadcasts = new LinkedList<InetAddress>();

        // Add global broadcast address
        try {
          broadcasts.add(InetAddress.getByName("255.255.255.255"));
        } catch (UnknownHostException e) {
        }

        // Add all broadcast addresses for all known links
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
          NetworkInterface networkInterface = interfaces.nextElement();
          if (networkInterface.isLoopback() || !networkInterface.isUp()) {
            continue; // Skip loopback and interfaces that are down
          }
          for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
            broadcasts.add(address.getBroadcast());
          }
        }

        // Send the beacon package on all braodcast addresses we got
        for (InetAddress address : broadcasts) {
          try {
            socket.send(
                new DatagramPacket(data.toByteArray(), data.toByteArray().length, address, 12354));
            // log.info("Beacon package sent to "+address.getHostAddress());
          } catch (Exception e) {
            // Ignore
          }
        }

      } catch (SocketException e) {
        log.warning("SocketException in beacon send block");
        log.warning(e.toString());
      } catch (IOException e) {
        log.warning("IOException in beacon send block");
        log.warning(e.toString());
      } finally {
        lastBeacon = System.currentTimeMillis();

        if (socket != null) {
          socket.close();
        }
      }
    }
    log.info("Beacon thread stopping");
  }