Ejemplo n.º 1
0
 public sendUDPBroadcastThread() {
   try {
     // Creates the socket
     if (socket == null) {
       socket = new DatagramSocket(null);
       socket.setReuseAddress(true);
       socket.setBroadcast(true);
       socket.bind(new InetSocketAddress(8080));
       socket.setBroadcast(true);
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 2
0
  public static void main(String[] args) {
    int port = 5555;

    DatagramSocket socket;
    socket = null;
    try {
      socket = new DatagramSocket(port);
      socket.setBroadcast(true);
      socket.connect(InetAddress.getByName("255.255.255.255"), 5555);
    } catch (Exception e) {
      System.err.println("Connection failed. " + e.getMessage());
    }

    while (true) {
      String message = "hey";
      byte[] buf = message.getBytes();

      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      try {
        socket.send(packet);
      } catch (Exception e) {
        System.err.println("Sending failed. " + e.getMessage());
      }
    }
  }
Ejemplo 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();
    }
  }
Ejemplo n.º 4
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();
    }
  }
Ejemplo n.º 5
0
  private static void setupService() {
    try {
      // setup webserver to listen on localhost:80
      Webserver server = new Webserver(80);

      // open broadcast socket on port 15000
      DatagramSocket broadcast_socket = new DatagramSocket();
      broadcast_socket.setBroadcast(true);

      // {optional} mac address hash
      String macHash = "12345678909876543212345678909876";
      // get IP address from this machine

      // Create broadcast message
      String broadcast_msg = "Sensor online, MACHash=" + macHash + ", IP=" + getIP();
      // Create broadcast packet
      DatagramPacket broadcast_packet =
          new DatagramPacket(
              broadcast_msg.getBytes(),
              broadcast_msg.getBytes().length,
              InetAddress.getByName("255.255.255.255"),
              15000);
      // Send Broadcast packet
      broadcast_socket.send(broadcast_packet);

    } catch (IOException ex) {
      Logger.getLogger(UserTrackerApplication.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 6
0
  @Override
  public void run() {

    DatagramSocket socket;
    int clientListnport = Constants.UDPPort;

    try {
      // Keep a socket open to listen to all the UDP trafic that is
      // destined for this port
      socket = new DatagramSocket(clientListnport, (Inet4Address) InetAddress.getByName("0.0.0.0"));
      socket.setBroadcast(true);
      socket.setSoTimeout(10000);

      while (WifiReceiver.isWifi) {
        System.out.println(">>>Ready to receive broadcast packets!");

        // Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        try {
          socket.receive(packet);

          // Packet received
          System.out.println(
              ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
          // See if the packet holds the right command (message)
          String message = new String(packet.getData()).trim();
          if (message.equals(Constants.serverDiscoverString)) {
            byte[] sendData = Constants.clientReplyString.getBytes();
            // Send a response

            if (!WifiUtils.getipAddress()
                .equalsIgnoreCase(packet.getAddress().getHostAddress().toString())) {
              DatagramPacket sendPacket =
                  new DatagramPacket(
                      sendData, sendData.length, packet.getAddress(), packet.getPort());
              socket.send(sendPacket);

              System.out.println(">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
            }
          } else if (message.equals(Constants.serverFileSending)) {
            System.out.println("sending reply to recive handshake");
            byte[] sendData = Constants.clientFileReceive.getBytes();
            DatagramPacket sendPacket =
                new DatagramPacket(
                    sendData, sendData.length, packet.getAddress(), packet.getPort());
            socket.send(sendPacket);
            Log.d(loggerTag, "handshaking is done");
            FileReceiver.waitConnection();
          }
        } catch (SocketTimeoutException e) {
          // no need of doing anything
        }
      }
      System.out.println("CLientListener : Listener is stoped");
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Ejemplo n.º 7
0
 public synchronized void init() {
   try {
     socket = new DatagramSocket();
     socket.setBroadcast(true);
     addr = InetAddress.getByName(castIP);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 8
0
  // Discovery thread
  @Override
  public void run() {

    while (!Thread.currentThread().isInterrupted()) {

      try {
        socket = new DatagramSocket(DISCOVERY_PORT, InetAddress.getByName("0.0.0.0"));
        socket.setBroadcast(true);

        // Keep an UDP Socket open
        while (!Thread.currentThread().isInterrupted() && socket.isBound()) {
          // Ready to receive sockets

          // Receive a packet
          byte[] rcvBuff = new byte[15000];
          DatagramPacket packet = new DatagramPacket(rcvBuff, rcvBuff.length);
          socket.receive(packet);

          // Packet received
          String msg = new String(packet.getData()).trim();
          if (msg.equals("REMOTECRAFT_DISCOVERY_REQUEST")) {
            // Attach world name
            String msgResponse =
                "REMOTECRAFT_DISCOVERY_RESPONSE:"
                    + String.valueOf(this.worldSeed)
                    + "_"
                    + this.worldName;
            byte[] sendData = msgResponse.getBytes();

            // Send response
            DatagramPacket sendPacket =
                new DatagramPacket(
                    sendData, sendData.length, packet.getAddress(), packet.getPort());
            if (socket.isBound()) {
              try {
                socket.send(sendPacket);
              } catch (Exception e) {
                e.printStackTrace();
              }
            } else {
              continue;
            }
          }
        }

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          socket.disconnect();
          socket.close();
        } catch (NullPointerException e) {
          e.printStackTrace();
        }
      }
    } // while !threadIsInterrupted
  }
Ejemplo n.º 9
0
  private void sendData(DatagramPacket packet, int localSendingPort) throws Exception {
    DatagramSocket sock = null;
    sock = new DatagramSocket(localSendingPort);
    sock.setReuseAddress(true);
    sock.setBroadcast(true);
    sock.send(packet);

    sock.close();
  }
Ejemplo n.º 10
0
  public Candidate discoverFromBroadcast()
      throws IOException, RetryException, ParserConfigurationException {

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

    sendBroadcast(socket);
    List<DatagramPacket> responses = collectBroadcastResponses(socket);
    return getCandidateFromDatagramResponses(responses);
  }
Ejemplo n.º 11
0
  @Override
  protected void open() throws IOException {
    Log.d(TAG, "Opening udp connection.");

    socket = (serverPort == -1) ? new DatagramSocket() : new DatagramSocket(serverPort);

    socket.setBroadcast(true);
    socket.setReuseAddress(true);
    socket.setSoTimeout(readTimeout);
  }
Ejemplo n.º 12
0
    // @Override
    // protected void onPreExecute() {
    //     Log.i("AsyncTask", "onPreExecute");
    // }
    @Override
    protected Boolean doInBackground(Void... params) {
      Log.i("AsyncTask", "doInBackground: Creating socket");

      while (networkConnection == true) {
        try {

          DatagramSocket client_socket = new DatagramSocket(null);
          client_socket.setReuseAddress(true);
          client_socket.setBroadcast(true);
          client_socket.bind(new InetSocketAddress(PORT));
          byte[] receiveData = new byte[1024];
          DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
          client_socket.receive(packet);
          modifiedSentence = new String(packet.getData(), 0, packet.getLength());
          Log.i("dostaje dane postaci", modifiedSentence);
          /*String pierwszy = Character.toString(modifiedSentence.charAt(0));
          Log.i("pierwszy znak to", pierwszy);*/

          t.start();

          u.start();

          client_socket.close();

        } catch (Throwable e) {
          e.printStackTrace();
        }

        // setUpMap();

        /*if (modifiedSentence.startsWith("$")) {
                    Log.i("parsuje", "nmee");
                    nmeaParser=new NmeaParser(modifiedSentence);
                    lat=nmeaParser.latitude;
                    lon=nmeaParser.longitude;
                    setUpMap();
                } else {
                    sensor.setTxtaccel_x();
                    sensor.setTxtaccel_y();
                    sensor.setTxtaccel_z();
                    sensor.setTxtmac_id();
                    sensor.setTxtid();
                    Log.d("set text", "dziala");
        }*/
      }

      return true;
    }
Ejemplo n.º 13
0
 public static void sendTo(String ip, int port, byte[] sendBuf) {
   try {
     if (_client == null) {
       _client = new DatagramSocket(null);
       _client.setReuseAddress(true);
       _client.setBroadcast(true); // 设置标志,T OR E OR R广播数据报
       // 在2.2左右版本不行。在4.0版本上可行
       _client.bind(new InetSocketAddress(port));
     }
     InetAddress address = InetAddress.getByName(ip);
     DatagramPacket sendpacket = new DatagramPacket(sendBuf, SEND_LENGHT, address, port);
     _client.setSoTimeout(2000);
     _client.send(sendpacket);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 14
0
 // ------------------------------------------------------------
 @Override
 public void run() {
   DatagramSocket ds;
   int numServers = Integer.valueOf(rb.getString("NumServers"));
   ServerDescription[] validServers = new ServerDescription[numServers];
   int expectedServers = 0;
   boolean addToFile = false, serverAdded;
   System.out.println("Started listening for subagent broadcasts");
   for (int i = 0; i < numServers; i++) validServers[i] = new ServerDescription();
   try {
     expectedServers = getExpectedServers(validServers);
   } catch (GenericException e) {
     System.out.println("Parse error in file, rejecting subagent");
   }
   int listenPort = Integer.valueOf(rb.getString("broadcastPort"));
   System.out.println("listen Port is " + listenPort);
   try {
     ds = new DatagramSocket(null);
     ds.setBroadcast(true);
     ds.setReuseAddress(true);
     ds.bind(new InetSocketAddress(listenPort));
   } catch (IOException e) {
     System.out.println("Error, broadcast socket not created successfully");
     System.out.println("Got message: " + e);
     return;
   }
   byte[] receiveData = new byte[1024];
   DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
   while (keepRunning) {
     try {
       ds.receive(receivePacket);
       System.out.println("Received a datagram packet");
       if (expectedServers < numServers) addToFile = true;
       else addToFile = false;
       serverAdded = respondToDatagram(receivePacket, validServers, addToFile, expectedServers);
       if (serverAdded) expectedServers++;
     } catch (IOException e) {
       System.out.println("Error, unable to connect with subagent");
       System.out.println("Got message: " + e);
     }
   } // end while (keepRunning)
 }
Ejemplo n.º 15
0
 // Broadcasts a packet containing server address to the LAN every second
 public void run() {
   try {
     DatagramSocket socket = new DatagramSocket();
     InetSocketAddress address = new InetSocketAddress("255.255.255.255", DISCOVERY_PORT);
     byte[] message = new byte[0];
     socket.setBroadcast(true);
     DatagramPacket packet = new DatagramPacket(message, message.length);
     packet.setSocketAddress(address);
     while (true) {
       socket.send(packet);
       Thread.sleep(1000);
     }
   } catch (IOException e) {
     // Port is in use, we don't know our own address or we could not send the broadcast for some
     // reason. Either way, discovery won't work.
     logger.log(Level.SEVERE, null, e);
   } catch (InterruptedException e) {
     logger.log(Level.INFO, "Discovery service shutting down");
   }
 }
Ejemplo n.º 16
0
  private void readPackets() {

    try {
      if (socket == null) {
        // InetAddress addr =
        // InetAddress.getByName(configuration.IP_HERMES);
        InetSocketAddress socketaddress = new InetSocketAddress(configuration.PORT_HERMES);
        socket = new DatagramSocket(socketaddress);
        socket.setReuseAddress(true);
        socket.setBroadcast(true);
        socket.setSoTimeout(100);
      }

      DatagramPacket datagram = new DatagramPacket(rxbuffer, rxbuffer.length);
      socket.receive(datagram);
      handlePacket(datagram);
    } catch (SocketException se) {
    } catch (IOException ioe) {
    }
  }
Ejemplo n.º 17
0
  public void start() throws Exception {
    for (int i = bind_port; i <= bind_port + port_range; i++) {
      try {
        sock = getSocketFactory().createDatagramSocket("jgroups.bping.sock", i);
        break;
      } catch (Throwable t) {
        if (i > bind_port + port_range)
          throw new RuntimeException(
              "failed to open a port in range ["
                  + bind_port
                  + " - "
                  + (bind_port + port_range)
                  + "]",
              t);
      }
    }

    sock.setBroadcast(true);
    startReceiver();
    super.start();
  }
Ejemplo n.º 18
0
  /**
   * 获取设备信息
   *
   * @param msg
   * @param listener
   */
  public static void receive(String msg, UdpCallBackListener listener) {
    ArrayList<String> responses = new ArrayList<String>();
    String Strs = "";
    try {
      if (_client == null) {
        _client = new DatagramSocket(null);
        _client.setReuseAddress(true);
        _client.setBroadcast(true); // 设置标志,T OR E OR R广播数据报
        // 在2.2左右版本不行。在4.0版本上可行
        _client.bind(new InetSocketAddress(port));
      }
      DatagramPacket sendDp =
          new DatagramPacket(
              msg.getBytes(), msg.getBytes().length, InetAddress.getByName(IP), port);
      _client.setSoTimeout(2000);
      _client.send(sendDp);
      byte[] buf = new byte[1024];
      DatagramPacket receiveDp = new DatagramPacket(buf, buf.length);

      // 创建长度为100的数据接收包
      while (true) {
        Thread.sleep(50);
        _client.receive(receiveDp); // 套接字接收数据包
        String tmpStr = new String(buf, 0, receiveDp.getLength()).replace(" ", "");
        Strs += tmpStr;
        if (tmpStr.contains(SEND_CODE) && tmpStr.contains(",0")) {
          String strdev = tmpStr + "|" + receiveDp.getAddress();
          if (responses.indexOf(strdev) == -1) responses.add(strdev);
        }
      }
    } catch (Exception e) {
      if (listener != null) {
        listener.onError(e);
      }
    }
    if (listener != null) {
      listener.onFinish(responses);
    }
  }
  /**
   * Constructor
   *
   * @param broadcastAddress destination address for probes
   * @param handler update Handler in main thread
   */
  public BroadcastDiscoveryClient(InetAddress broadcastAddress, Handler handler) {
    mBroadcastAddress = broadcastAddress;
    mHandler = handler;

    try {
      mSocket = new DatagramSocket(); // binds to random port
      mSocket.setBroadcast(true);
    } catch (SocketException e) {
      Log.e(LOG_TAG, "Could not create broadcast client socket.", e);
      throw new RuntimeException();
    }

    mProbeTimer = new Timer();
    mProbeTimerTask =
        new TimerTask() {
          @Override
          public void run() {
            BroadcastDiscoveryClient.this.sendProbe();
          }
        };
    Log.i(LOG_TAG, "Starting client on address " + mBroadcastAddress);
  }
Ejemplo n.º 20
0
  public CopyOfUdpClient(byte[] bytes) {
    try {
      udp = new DatagramSocket();
      // 设置广播开关
      udp.setBroadcast(false);
      //			recdp = new DatagramPacket(bytes, bytes.length,
      //					InetAddress.getByName("219.150.156.51"), UDP_PORT);
      recdp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("127.0.0.1"), UDP_PORT);
      udp.send(recdp);
      udp.close();

    } catch (SocketException e) {
      System.out.println("创建端口监听客户端失败" + e);
      e.printStackTrace();
    } catch (UnknownHostException ex) {
      System.out.println("UnknownHostException" + ex);
      ex.printStackTrace();
    } catch (IOException e) {
      System.out.println("发送失败" + e);
      e.printStackTrace();
    }
  }
Ejemplo n.º 21
0
  @Override
  public void run() {
    try {
      // Keep a socket open to listen to all the UDP trafic that is
      // destined for this port
      socket = new DatagramSocket(8888, InetAddress.getByName("0.0.0.0"));
      socket.setBroadcast(true);

      while (true) {
        log.info("server >>>Ready to receive broadcast packets! on 0.0.0.0:8888");

        // Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        socket.receive(packet);

        // Packet received
        log.info(
            "server >>>Discovery packet received from: " + packet.getAddress().getHostAddress());
        log.info("server >>>Packet received; data: " + new String(packet.getData()));

        // See if the packet holds the right command (message)
        String message = new String(packet.getData()).trim();
        if (message.equals("DISCOVER_FUIFSERVER_REQUEST")) {
          byte[] sendData = "DISCOVER_FUIFSERVER_RESPONSE".getBytes();

          // Send a response
          DatagramPacket sendPacket =
              new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
          socket.send(sendPacket);

          log.info("server >>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
        }
      }
    } catch (Exception e) {
      Logging.logException(e);
    }
  }
  @Override
  public void setBroadcast(boolean broadcast) {
    try {
      // See: https://github.com/netty/netty/issues/576
      if (broadcast
          && !DetectionUtil.isWindows()
          && !DetectionUtil.isRoot()
          && !socket.getLocalAddress().isAnyLocalAddress()) {
        // Warn a user about the fact that a non-root user can't receive a
        // broadcast packet on *nix if the socket is bound on non-wildcard address.
        logger.warn(
            "A non-root user can't receive a broadcast packet if the socket "
                + "is not bound to a wildcard address; setting the SO_BROADCAST flag "
                + "anyway as requested on the socket which is bound to "
                + socket.getLocalSocketAddress()
                + '.');
      }

      socket.setBroadcast(broadcast);
    } catch (SocketException e) {
      throw new ChannelException(e);
    }
  }
Ejemplo n.º 23
0
 @Override
 public void run() {
   // Open for voting
   logger.log(Level.INFO, "Beginning voting");
   voting.beginVoting();
   VotingReceiver votingService = new VotingReceiver();
   if (votingThread != null && !votingThread.isInterrupted()) {
     votingThread.interrupt();
   }
   votingThread = new Thread(votingService);
   votingThread.start();
   try {
     /*If client/server are on the same machine, broadcast may arrive at client
      * before server opens receive socket. This is not relevant on separate machines
      * but it avoids an extra voting cycle on single machine tests.
      */
     Thread.sleep(200);
     // Broadcast start of voting period
     try {
       DatagramSocket socket = new DatagramSocket();
       InetSocketAddress address = new InetSocketAddress("255.255.255.255", VOTING_PORT);
       byte[] message = new byte[0];
       socket.setBroadcast(true);
       DatagramPacket packet = new DatagramPacket(message, message.length);
       packet.setSocketAddress(address);
       socket.send(packet);
     } catch (IOException e) {
       logger.log(Level.SEVERE, null, e);
     }
     Thread.sleep(10000); // Run voting for 10 seconds
   } catch (InterruptedException ex) {
     logger.log(Level.INFO, "Voting shutting down");
   }
   votingThread.interrupt();
   voting.endVoting(MCServer.this);
 }
Ejemplo n.º 24
0
    @Override
    public void run() {
      DatagramSocket socket = null;
      try {
        socket = new DatagramSocket(PORT);
        socket.setReuseAddress(true);
        socket.setBroadcast(true);

        try {
          while (mTransmit) {
            byte[] buffer = new byte[Packet.LENGTH];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);

            final Packet p = new Packet(buffer);
            if (!p.mValid) {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      mScreen.setBackgroundColor(Color.rgb(255, 255, 0));
                    }
                  });
              Log.w(TAG, "Got bogus message");
              continue;
            }

            // Handle keep alive
            if (mKeepAliveThread != null && mKeepAliveThread.mInterval != p.mKeepAliveInterval) {
              mKeepAliveThread.stopTransmission();
              try {
                mKeepAliveThread.join();
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              mKeepAliveThread = null;
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      mKeepAliveText.setText("");
                    }
                  });
            }

            if (mKeepAliveThread == null && p.mKeepAliveInterval != 0) {

              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      mKeepAliveText.setText("" + p.mKeepAliveInterval);
                    }
                  });
              mKeepAliveThread =
                  new KeepAliveThread(packet.getAddress().getHostAddress(), p.mKeepAliveInterval);
              mKeepAliveThread.start();
            }

            // We got a sequence number below that of the previous - reset!
            if (mLastPacket > p.mPacketNumber) {
              mLastPacket = 0;
              mLostPackets = 0;
              mPacketCount = 0;
            }

            if (mLastPacket != 0) {
              mLostPackets += (p.mPacketNumber - mLastPacket) - 1;
            }
            mLastPacket = p.mPacketNumber;

            mPacketCount += 1;
            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    resetAnimation(p.mSendInterval);
                    mLastPacketText.setText("" + p.mPacketNumber);
                    mPacketCountText.setText("" + mPacketCount);
                    mLostPacketsText.setText("" + mLostPackets);
                  }
                });
          }
        } catch (IOException e) {
          e.printStackTrace();
        }

      } catch (SocketException e) {
        e.printStackTrace();
      } finally {
        if (socket != null) {
          socket.close();
        }
      }
    }
Ejemplo n.º 25
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    while (running) {
      if (isDebug) Log.i(TAG, "5s扫描设备>>>>>>>>>>>>" + Thread.currentThread());
      receive = 50; // 最大接收数量
      isSend = false;
      String recestr = null;
      try {
        listDevices.clear();
        sendSocket = new DatagramSocket();
        sendSocket.setBroadcast(true);
        sendSocket.setSoTimeout(3000);
        sendSocket.send(sendPacket);
        while (receive-- > 0) {
          sendSocket.receive(recePacket);
          recestr = new String(recedata, recePacket.getOffset(), recePacket.getLength());
          if (recestr.startsWith(DISCOVERY_RESP)) {
            Device device = new Device();
            device.setDeviceName(recestr.substring(9));
            device.setDeviceIp(recePacket.getAddress().getHostAddress());
            if (listDevices.indexOf(device) < 0) {
              listDevices.add(device);
              if (device.getDeviceIp().equals("10.8.8.1")) {
                isSend = true;
                if (isDebug) Log.i(TAG, "扫描到10.8.8.1" + listDevices + "|" + Thread.currentThread());
                sendResult();
                break;
              }
            }
          }

          // 每次接收完UDP数据后,重置长度。否则可能会导致下次收到数据包被截断。
          recePacket.setLength(default_bufferSize);
        }
      } catch (SocketTimeoutException e) {
        if (isDebug) Log.i(TAG, "扫描3s超时" + listDevices + "|" + Thread.currentThread());
        if (!isSend) {
          sendResult();
        }
      } catch (SocketException e) {
        receive = 0;
        if (isDebug) Log.i(TAG, "SocketException>>>>>>" + Thread.currentThread());
        if (mScanListener != null) {
          mScanListener.scanException();
        }
      } catch (IOException e) {
        receive = 0;
        if (isDebug) Log.i(TAG, "SocketException>>>>>>" + Thread.currentThread());
        if (mScanListener != null) {
          mScanListener.scanException();
        }
      }
      sendSocket.close();

      if (wipicoVersion >= 2) {
        // 版本2才进行SSID 扫描
        List<ScanResult> listScanResults = WifiAdmin.getInstance(mContext).getScanResults();
        if (listScanResults != null) {
          for (ScanResult bean : listScanResults) {
            if (DeviceUtil.isMatchSSID(DeviceUtil.ssidCorrect(bean.SSID))) {
              listWifiDevices.add(
                  new Device(DeviceUtil.ssidCorrect(bean.SSID), bean.capabilities, null));
            }
          }
        }
        sendWifiResult();
      }

      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 26
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;
  }
    @Override
    protected Void doInBackground(Void... params) {
      Log.d("Discovery: ", "start UDP Server");
      String data = "0::deskcon";
      try {
        // Send "Ask for Hosts" Broadcast
        serverSocketUDP = new DatagramSocket(5108);
        serverSocketUDP.setBroadcast(true);

        InetAddress local = getBroadcast();

        // has a broadcast address been found
        if (local == null) {
          Log.d("Discovery: ", "no Broadcast Address found");
          return null;
        }

        DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), local, 5108);
        serverSocketUDP.send(packet);

      } catch (Exception e) {
        e.printStackTrace();
        Log.d("Discovery: ", "could not start");
        return null;
      }

      WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
      MulticastLock lock = wifi.createMulticastLock("net.screenfreeze.deskcon");
      lock.acquire();

      // Receive responses from desktop hosts
      while (!isStopped) {
        byte[] receiveData = new byte[128];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        try {
          serverSocketUDP.receive(receivePacket);
        } catch (Exception e) {
        }

        final InetAddress address = receivePacket.getAddress();

        String msg = new String(receiveData, 0, receivePacket.getLength());

        // Check for valid msg
        boolean isvalismsg = msg.split("::").length == 3;

        // Process msg if it is not our own broadcast msg
        if (!msg.equals(data) && !isStopped && isvalismsg) {

          final DesktopHost desktop = handleReceiveUdp(msg, address);
          Log.d("udp from: ", "msg " + msg + "  " + address);

          runOnUiThread(
              new Runnable() {

                @Override
                public void run() {
                  dha.add(desktop);
                }
              });
        }
      }
      lock.release();

      return null;
    }
  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;
  }
Ejemplo n.º 29
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;
  }
Ejemplo n.º 30
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");
  }