Ejemplo n.º 1
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.º 2
0
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
Ejemplo n.º 3
0
  /*
   * Connect a UDP socket, disconnect it, then send and recv on it.
   * It will fail on Linux if we don't silently bind(2) again at the
   * end of DatagramSocket.disconnect().
   */
  private static void testConnectedUDP(InetAddress addr) throws Exception {
    try {
      DatagramSocket s = new DatagramSocket(0, addr);
      DatagramSocket ss = new DatagramSocket(0, addr);
      System.out.print("\tconnect...");
      s.connect(ss.getLocalAddress(), ss.getLocalPort());
      System.out.print("disconnect...");
      s.disconnect();

      byte[] data = {0, 1, 2};
      DatagramPacket p =
          new DatagramPacket(data, data.length, s.getLocalAddress(), s.getLocalPort());
      s.setSoTimeout(10000);
      System.out.print("send...");
      s.send(p);
      System.out.print("recv...");
      s.receive(p);
      System.out.println("OK");

      ss.close();
      s.close();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
Ejemplo n.º 4
0
 @Override
 public void connect() {
   try {
     clientSide = new DatagramSocket();
     clientSide.connect(this.ip, this.port);
   } catch (Exception error) {
     System.out.print("could't to connect to server because : " + error.getMessage());
   }
 }
Ejemplo n.º 5
0
  public void start() throws IOException {
    socket.connect(new InetSocketAddress(host, port));

    byte[] buffer = new byte[1];

    for (int i = 0; i < packagesQtt; i++) {
      String send =
          String.valueOf(i)
              + "@"
              + sausage; // Calendar.getInstance().getTimeInMillis()+".mensagem:"+i+sausage;
      buffer = send.getBytes();
      System.out.println(send);
      socket.send(new DatagramPacket(buffer, buffer.length));
    }

    buffer = new byte[512];
    DatagramPacket response = new DatagramPacket(buffer, buffer.length);
    byte[] responseBuffer = null;
    int timer = 0;

    try {
      Thread.sleep(200);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("Recebendo!");
    int previous = -1;
    while (true) {
      socket.receive(response);
      responseBuffer = response.getData();
      String ans = new String(responseBuffer);
      if (testSequence) {
        int value = Integer.valueOf(ans.split("@")[0]);
        if (value != previous + 1) {
          System.out.printf("ERRO! Previous %d e Atual: %d\n", previous, value);
          break;
        }
        previous = value;
      }
      int l = response.getLength();
      ans = ans.substring(0, l);
      System.out.println(ans);
      answers.add(ans);
      timer++;

      if (timer == packagesQtt) {
        break;
      }
    }

    for (String msg : answers) {
      System.out.println(answers.size() + " " + msg);
    }
    System.out.println("Quantidade Recebida: " + answers.size());
  }
Ejemplo n.º 6
0
 private String determineLocalIp() {
   try {
     DatagramSocket s = new DatagramSocket();
     s.connect(InetAddress.getByName("192.168.1.1"), 80);
     return s.getLocalAddress().getHostAddress();
   } catch (IOException e) {
     if (DEBUG) Log.d(TAG, "determineLocalIp()", e);
     // dont do anything; there should be a connectivity change going
     return null;
   }
 }
Ejemplo n.º 7
0
  /** Generic constructor for the name service interface */
  public LeetActive(String svc_host, int svc_port, int portNum) {

    try {
      nameServer = new DatagramSocket();
      nameServer.setSoTimeout(3000);
      nameServer.connect(InetAddress.getByName(svc_host), svc_port);
    } catch (Exception e) {
      System.err.println("LA " + e);
    }
    this.portNum = portNum;
    hostList = new ArrayList();
  }
Ejemplo n.º 8
0
  public MockClient(String host, int port, int userid) {
    this.userid = userid;
    try {
      ds = new DatagramSocket();
      ds.connect(InetAddress.getByName(host), port);
    } catch (SocketException | UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    cs = new ClientState(userid);
    cs.yVote = 50;
  }
Ejemplo n.º 9
0
  public void start() throws IOException {
    sendSocket = new DatagramSocket();
    sendSocket.connect(new InetSocketAddress(ipAddress, port));
    /*try
    {
    	Thread.sleep(1000);
    	sendSocket = new DatagramSocket();
    	sendSocket.connect(new InetSocketAddress(ipAddress, port));
    }
    catch(InterruptedException ie)
    {
    	System.err.println("Caught interrupted exception while starting");
    }*/

  }
Ejemplo n.º 10
0
  /**
   * Connect to Avatar.
   *
   * @throws IOException if the connection to Avatar could not be established
   */
  private void connect() throws IOException {
    // Do nothing if we are already connectd.
    if (socket != null) {
      return;
    }

    // Connect to Avatar
    if (host == null) {
      host = InetAddress.getLocalHost();
    }
    socket = new DatagramSocket();
    socket.connect(host, port);
    LOGGER.info("connected to Avatar at '" + host + ":" + port);
    feedback = new BMLFeedback(this, feedbackPort);
    feedback.start();
  }
  /**
   * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon
   * or distribute to peers as a contact address.
   *
   * @param intendedDestination the destination that we'd like to use the localhost address with.
   * @return an InetAddress instance representing the local host, and that a socket can bind upon or
   *     distribute to peers as a contact address.
   */
  public synchronized InetAddress getLocalHost(InetAddress intendedDestination) {
    // no point in making sure that the localHostFinderSocket is initialized.
    // better let it through a NullPointerException.
    InetAddress localHost = null;
    localHostFinderSocket.connect(intendedDestination, this.RANDOM_ADDR_DISC_PORT);
    localHost = localHostFinderSocket.getLocalAddress();
    localHostFinderSocket.disconnect();
    // windows socket implementations return the any address so we need to
    // find something else here ... InetAddress.getLocalHost seems to work
    // better on windows so lets hope it'll do the trick.
    if (localHost.isAnyLocalAddress()) {
      try {
        // all that's inside the if is an ugly IPv6 hack
        // (good ol' IPv6 - always causing more problems than it solves.)
        if (intendedDestination instanceof Inet6Address) {
          // return the first globally routable ipv6 address we find
          // on the machine (and hope it's a good one)
          Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

          while (interfaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface) interfaces.nextElement();
            Enumeration addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
              InetAddress address = (InetAddress) addresses.nextElement();
              if (address instanceof Inet6Address) {
                if (!address.isAnyLocalAddress()
                    && !address.isLinkLocalAddress()
                    && !address.isSiteLocalAddress()
                    && !address.isLoopbackAddress()) {
                  return address;
                }
              }
            }
          }
        } else localHost = InetAddress.getLocalHost();
        /** @todo test on windows for ipv6 cases */
      } catch (Exception ex) {
        // sigh ... ok return 0.0.0.0
        logger.warn("Failed to get localhost ", ex);
      }
    }

    return localHost;
  }
Ejemplo n.º 12
0
  /**
   * Attempts to establish a connection.
   *
   * @throws UnknownHostException - if the host is unknown.
   */
  public void connect() throws UnknownHostException {
    socket.connect(InetAddress.getByName(address), port);

    if (debug) System.out.println("Connected");
  }
Ejemplo n.º 13
0
  /**
   * Send an array of bytes.
   *
   * @param receiverAddress -- inet address
   * @param contactPort -- port to connect to.
   * @param transport -- tcp or udp.
   * @param retry -- retry to connect if the other end closed connection
   * @throws IOException -- if there is an IO exception sending message.
   */
  public Socket sendBytes(
      InetAddress senderAddress,
      InetAddress receiverAddress,
      int contactPort,
      String transport,
      byte[] bytes,
      boolean retry)
      throws IOException {
    int retry_count = 0;
    int max_retry = retry ? 2 : 1;
    // Server uses TCP transport. TCP client sockets are cached
    int length = bytes.length;
    if (sipStack.isLoggingEnabled()) {
      sipStack.logWriter.logDebug(
          "sendBytes "
              + transport
              + " inAddr "
              + receiverAddress.getHostAddress()
              + " port = "
              + contactPort
              + " length = "
              + length);
    }
    if (transport.compareToIgnoreCase(TCP) == 0) {
      String key = makeKey(receiverAddress, contactPort);
      // This should be in a synchronized block ( reported by
      // Jayashenkhar ( lucent ).

      try {
        boolean retval =
            this.ioSemaphore.tryAcquire(
                10000, TimeUnit.MILLISECONDS); // TODO - make this a stack config parameter?
        if (!retval) {
          throw new IOException("Could not acquire IO Semaphore after 10 second -- giving up ");
        }
      } catch (InterruptedException ex) {
        throw new IOException("exception in aquiring sem");
      }
      Socket clientSock = getSocket(key);

      try {

        while (retry_count < max_retry) {
          if (clientSock == null) {
            if (sipStack.isLoggingEnabled()) {
              sipStack.logWriter.logDebug("inaddr = " + receiverAddress);
              sipStack.logWriter.logDebug("port = " + contactPort);
            }
            // note that the IP Address for stack may not be
            // assigned.
            // sender address is the address of the listening point.
            // in version 1.1 all listening points have the same IP
            // address (i.e. that of the stack). In version 1.2
            // the IP address is on a per listening point basis.
            clientSock =
                sipStack
                    .getNetworkLayer()
                    .createSocket(receiverAddress, contactPort, senderAddress);
            OutputStream outputStream = clientSock.getOutputStream();
            writeChunks(outputStream, bytes, length);
            putSocket(key, clientSock);
            break;
          } else {
            try {
              OutputStream outputStream = clientSock.getOutputStream();
              writeChunks(outputStream, bytes, length);
              break;
            } catch (IOException ex) {
              if (sipStack.isLoggingEnabled()) sipStack.logWriter.logException(ex);
              // old connection is bad.
              // remove from our table.
              removeSocket(key);
              try {
                clientSock.close();
              } catch (Exception e) {
              }
              clientSock = null;
              retry_count++;
            }
          }
        }
      } finally {
        ioSemaphore.release();
      }

      if (clientSock == null) {
        throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort);
      } else return clientSock;

      // Added by Daniel J. Martinez Manzano <*****@*****.**>
      // Copied and modified from the former section for TCP
    } else if (transport.compareToIgnoreCase(TLS) == 0) {
      String key = makeKey(receiverAddress, contactPort);
      try {
        boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
        if (!retval) throw new IOException("Timeout aquiring IO SEM");
      } catch (InterruptedException ex) {
        throw new IOException("exception in aquiring sem");
      }
      Socket clientSock = getSocket(key);
      try {
        while (retry_count < max_retry) {
          if (clientSock == null) {
            if (sipStack.isLoggingEnabled()) {
              sipStack.logWriter.logDebug("inaddr = " + receiverAddress);
              sipStack.logWriter.logDebug("port = " + contactPort);
            }
            if (!sipStack.useTlsAccelerator) {
              clientSock =
                  sipStack
                      .getNetworkLayer()
                      .createSSLSocket(receiverAddress, contactPort, senderAddress);
            } else {
              clientSock =
                  sipStack
                      .getNetworkLayer()
                      .createSocket(receiverAddress, contactPort, senderAddress);
            }
            OutputStream outputStream = clientSock.getOutputStream();
            writeChunks(outputStream, bytes, length);
            putSocket(key, clientSock);
            break;
          } else {
            try {
              OutputStream outputStream = clientSock.getOutputStream();
              writeChunks(outputStream, bytes, length);
              break;
            } catch (IOException ex) {
              if (sipStack.isLoggingEnabled()) sipStack.logWriter.logException(ex);
              // old connection is bad.
              // remove from our table.
              removeSocket(key);
              try {
                clientSock.close();
              } catch (Exception e) {
              }
              clientSock = null;
              retry_count++;
            }
          }
        }
      } finally {
        ioSemaphore.release();
      }
      if (clientSock == null) {
        throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort);
      } else return clientSock;

    } else {
      // This is a UDP transport...
      DatagramSocket datagramSock = sipStack.getNetworkLayer().createDatagramSocket();
      datagramSock.connect(receiverAddress, contactPort);
      DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length, receiverAddress, contactPort);
      datagramSock.send(dgPacket);
      datagramSock.close();
      return null;
    }
  }
Ejemplo n.º 14
0
  private boolean test1()
      throws UtilityException, SocketException, UnknownHostException, IOException,
          MessageAttributeParsingException, MessageHeaderParsingException {
    int timeSinceFirstTransmission = 0;
    int timeout = timeoutInitValue;
    while (true) {
      try {
        // Test 1 including response
        socketTest1 = new DatagramSocket(new InetSocketAddress(localAddress, localPort));
        socketTest1.setReuseAddress(true);
        socketTest1.connect(InetAddress.getByName(stunServer), stunPort);
        socketTest1.setSoTimeout(timeout);

        LOGGER.debug("!!!!! SocketAddress: " + socketTest1.getLocalSocketAddress());

        MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
        sendMH.generateTransactionID();

        ChangeRequest changeRequest = new ChangeRequest();
        sendMH.addMessageAttribute(changeRequest);

        byte[] data = sendMH.getBytes();
        DatagramPacket send = new DatagramPacket(data, data.length);
        socketTest1.send(send);
        LOGGER.debug("Test 1: Binding Request sent.");

        MessageHeader receiveMH = new MessageHeader();
        while (!(receiveMH.equalTransactionID(sendMH))) {
          DatagramPacket receive = new DatagramPacket(new byte[200], 200);
          socketTest1.receive(receive);
          receiveMH = MessageHeader.parseHeader(receive.getData());
          receiveMH.parseAttributes(receive.getData());
        }

        ma =
            (MappedAddress)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
        ca =
            (ChangedAddress)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ChangedAddress);
        ErrorCode ec =
            (ErrorCode)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
        if (ec != null) {
          di.setError(ec.getResponseCode(), ec.getReason());
          LOGGER.debug("Message header contains an Errorcode message attribute.");
          return false;
        }
        if ((ma == null) || (ca == null)) {
          di.setError(
              700,
              "The server is sending an incomplete response (Mapped Address and Changed Address message attributes are missing). The client should not retry.");
          LOGGER.debug(
              "Response does not contain a Mapped Address or Changed Address message attribute.");
          return false;
        } else {
          di.setPublicIP(ma.getAddress().getInetAddress());
          di.setLocalPort(socketTest1.getLocalPort());
          if ((ma.getPort() == socketTest1.getLocalPort())
              && (ma.getAddress().getInetAddress().equals(socketTest1.getLocalAddress()))) {
            LOGGER.debug("Node is not natted.");
            di.setPublicPort(socketTest1.getLocalPort());
            nodeNatted = false;
          } else {
            di.setPublicPort(ma.getPort());
            LOGGER.debug("Node is natted.");
          }
          return true;
        }
      } catch (SocketTimeoutException ste) {
        if (timeSinceFirstTransmission < timeoutTest) {
          LOGGER.debug("Test 1: Socket timeout while receiving the response.");
          timeSinceFirstTransmission += timeout;
          int timeoutAddValue = (timeSinceFirstTransmission * 2);
          if (timeoutAddValue > timeoutSecond) // 1600)
          timeoutAddValue = timeoutSecond;
          timeout = timeoutAddValue;
        } else {
          // node is not capable of udp communication
          LOGGER.debug(
              "Test 1: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
          di.setBlockedUDP();
          LOGGER.debug("Node is not capable of UDP communication.");
          return false;
        }
      }
    }
  }
Ejemplo n.º 15
0
  private boolean test2()
      throws UtilityException, SocketException, UnknownHostException, IOException,
          MessageAttributeParsingException, MessageAttributeException,
          MessageHeaderParsingException {
    int timeSinceFirstTransmission = 0;
    int timeout = timeoutInitValue;
    while (true) {
      try {
        // Test 2 including response
        DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(localAddress, 0));
        sendSocket.connect(InetAddress.getByName(stunServer), stunPort);
        sendSocket.setSoTimeout(timeout);

        MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
        sendMH.generateTransactionID();

        ChangeRequest changeRequest = new ChangeRequest();
        changeRequest.setChangeIP();
        changeRequest.setChangePort();
        sendMH.addMessageAttribute(changeRequest);

        byte[] data = sendMH.getBytes();
        DatagramPacket send = new DatagramPacket(data, data.length);
        sendSocket.send(send);
        LOGGER.debug("Test 2: Binding Request sent.");

        int localPort = sendSocket.getLocalPort();
        InetAddress localAddress = sendSocket.getLocalAddress();

        sendSocket.close();

        DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
        receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort());
        receiveSocket.setSoTimeout(timeout);

        MessageHeader receiveMH = new MessageHeader();
        while (!(receiveMH.equalTransactionID(sendMH))) {
          DatagramPacket receive = new DatagramPacket(new byte[200], 200);
          receiveSocket.receive(receive);
          receiveMH = MessageHeader.parseHeader(receive.getData());
          receiveMH.parseAttributes(receive.getData());
        }
        ErrorCode ec =
            (ErrorCode)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
        if (ec != null) {
          di.setError(ec.getResponseCode(), ec.getReason());
          LOGGER.debug("Message header contains an Errorcode message attribute.");
          return false;
        }
        if (!nodeNatted) {
          di.setOpenAccess();
          LOGGER.debug(
              "Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation).");
        } else {
          di.setFullCone();
          LOGGER.debug("Node is behind a full-cone NAT.");
        }
        return false;
      } catch (SocketTimeoutException ste) {
        if (timeSinceFirstTransmission < timeoutTest) {
          LOGGER.debug("Test 2: Socket timeout while receiving the response.");
          timeSinceFirstTransmission += timeout;
          int timeoutAddValue = (timeSinceFirstTransmission * 2);
          if (timeoutAddValue > timeoutSecond) // 1600)
          timeoutAddValue = timeoutSecond;
          timeout = timeoutAddValue;
        } else {
          LOGGER.debug(
              "Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
          if (!nodeNatted) {
            di.setSymmetricUDPFirewall();
            LOGGER.debug("Node is behind a symmetric UDP firewall.");
            return false;
          } else {
            // not is natted
            // redo test 1 with address and port as offered in the changed-address message attribute
            return true;
          }
        }
      }
    }
  }
Ejemplo n.º 16
0
  private boolean test1Redo()
      throws UtilityException, SocketException, UnknownHostException, IOException,
          MessageAttributeParsingException, MessageHeaderParsingException {
    int timeSinceFirstTransmission = 0;
    int timeout = timeoutInitValue;
    while (true) {
      // redo test 1 with address and port as offered in the changed-address message attribute
      try {
        // Test 1 with changed port and address values
        socketTest1.connect(ca.getAddress().getInetAddress(), ca.getPort());
        socketTest1.setSoTimeout(timeout);

        MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
        sendMH.generateTransactionID();

        ChangeRequest changeRequest = new ChangeRequest();
        sendMH.addMessageAttribute(changeRequest);

        byte[] data = sendMH.getBytes();
        DatagramPacket send = new DatagramPacket(data, data.length);
        socketTest1.send(send);
        LOGGER.debug("Test 1 redo with changed address: Binding Request sent.");

        MessageHeader receiveMH = new MessageHeader();
        while (!(receiveMH.equalTransactionID(sendMH))) {
          DatagramPacket receive = new DatagramPacket(new byte[200], 200);
          socketTest1.receive(receive);
          receiveMH = MessageHeader.parseHeader(receive.getData());
          receiveMH.parseAttributes(receive.getData());
        }
        MappedAddress ma2 =
            (MappedAddress)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
        ErrorCode ec =
            (ErrorCode)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
        if (ec != null) {
          di.setError(ec.getResponseCode(), ec.getReason());
          LOGGER.debug("Message header contains an Errorcode message attribute.");
          return false;
        }
        if (ma2 == null) {
          di.setError(
              700,
              "The server is sending an incomplete response (Mapped Address message attribute is missing). The client should not retry.");
          LOGGER.debug("Response does not contain a Mapped Address message attribute.");
          return false;
        } else {
          if ((ma.getPort() != ma2.getPort())
              || (!(ma.getAddress().getInetAddress().equals(ma2.getAddress().getInetAddress())))) {
            di.setSymmetric();
            LOGGER.debug("Node is behind a symmetric NAT.");
            return false;
          }
        }
        return true;
      } catch (SocketTimeoutException ste2) {
        if (timeSinceFirstTransmission < timeoutTest) {
          LOGGER.debug(
              "Test 1 redo with changed address: Socket timeout while receiving the response.");
          timeSinceFirstTransmission += timeout;
          int timeoutAddValue = (timeSinceFirstTransmission * 2);
          if (timeoutAddValue > timeoutSecond) // 1600)
          timeoutAddValue = timeoutSecond;
          timeout = timeoutAddValue;
        } else {
          LOGGER.debug(
              "Test 1 redo with changed address: Socket timeout while receiving the response.  Maximum retry limit exceed. Give up.");
          return false;
        }
      }
    }
  }
Ejemplo n.º 17
0
  private void test3()
      throws UtilityException, SocketException, UnknownHostException, IOException,
          MessageAttributeParsingException, MessageAttributeException,
          MessageHeaderParsingException {
    int timeSinceFirstTransmission = 0;
    int timeout = timeoutInitValue;
    while (true) {
      try {
        // Test 3 including response
        DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(localAddress, 0));
        sendSocket.connect(InetAddress.getByName(stunServer), stunPort);
        sendSocket.setSoTimeout(timeout);

        MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
        sendMH.generateTransactionID();

        ChangeRequest changeRequest = new ChangeRequest();
        changeRequest.setChangePort();
        sendMH.addMessageAttribute(changeRequest);

        byte[] data = sendMH.getBytes();
        DatagramPacket send = new DatagramPacket(data, data.length);
        sendSocket.send(send);
        LOGGER.debug("Test 3: Binding Request sent.");

        int localPort = sendSocket.getLocalPort();
        InetAddress localAddress = sendSocket.getLocalAddress();

        sendSocket.close();

        DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
        receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort());
        receiveSocket.setSoTimeout(timeout);

        MessageHeader receiveMH = new MessageHeader();
        while (!(receiveMH.equalTransactionID(sendMH))) {
          DatagramPacket receive = new DatagramPacket(new byte[200], 200);
          receiveSocket.receive(receive);
          receiveMH = MessageHeader.parseHeader(receive.getData());
          receiveMH.parseAttributes(receive.getData());
        }
        ErrorCode ec =
            (ErrorCode)
                receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
        if (ec != null) {
          di.setError(ec.getResponseCode(), ec.getReason());
          LOGGER.debug("Message header contains an Errorcode message attribute.");
          return;
        }
        if (nodeNatted) {
          di.setRestrictedCone();
          LOGGER.debug("Node is behind a restricted NAT.");
          return;
        }
      } catch (SocketTimeoutException ste) {
        if (timeSinceFirstTransmission < timeoutTest) {
          LOGGER.debug("Test 3: Socket timeout while receiving the response.");
          timeSinceFirstTransmission += timeout;
          int timeoutAddValue = (timeSinceFirstTransmission * 2);
          if (timeoutAddValue > timeoutSecond) // 1600)
          timeoutAddValue = timeoutSecond;
          timeout = timeoutAddValue;
        } else {
          LOGGER.debug(
              "Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
          di.setPortRestrictedCone();
          LOGGER.debug("Node is behind a port restricted NAT.");
          return;
        }
      }
    }
  }
Ejemplo n.º 18
0
  public static void main(String[] args) {

    if (args.length < 4) {
      System.err.println(
          "Bad parameters: Paramters(s): <server (name or Ip address)> <port> <Op> <Payload>");
      return;
    }

    InetAddress server;
    int port;
    JackMessageOpType op;
    String payload;

    try {
      server = InetAddress.getByName(args[0]);

      port = Integer.parseInt(args[1]);
      if (!NamePortPair.isValidPort(port)) {
        System.err.println("Bad parameters: port must be an integer 1-65535");
        return;
      }

      if (args[2].length() != 1) {
        System.err.println("Bad parameters: op must be a single character");
        return;
      }
      op = JackMessageOpType.getTypeByOpCode(args[2].charAt(0));
      if (op == null) {
        System.err.println("Bad parameters: " + args[2].charAt(0) + " is not a valid op");
        return;
      }

      payload = args[3];
    } catch (NumberFormatException e) {
      System.err.println("Bad parameters: could not parse port");
      return;
    } catch (UnknownHostException e) {
      System.err.println("Communication problem: unable to find server");
      return;
    }

    DatagramSocket clientSocket;

    try {
      clientSocket = new DatagramSocket();
      clientSocket.connect(server, port);
      clientSocket.setSoTimeout(RESPONSE_WAIT_TIMEOUT);
    } catch (IOException e) {
      System.err.println(
          "Communication problem: could connect to " + server.getHostAddress() + ":" + port);
      e.printStackTrace();
      return;
    }

    Message msgToSend;
    DatagramPacket toSend;
    try {
      String msgString = (op.getOpCode() + " " + payload);
      msgToSend = Message.decode(msgString.getBytes(StandardCharsets.US_ASCII));
      toSend = new DatagramPacket(msgToSend.encode(), msgToSend.encode().length);
      clientSocket.send(toSend);
    } catch (NullPointerException | IllegalArgumentException e) {
      System.err.println("Bad parameters: invalid payload " + e.getMessage());
      terminateSocket(clientSocket);
      return;
    } catch (IOException e) {
      System.err.println("Communication problem: send");
      terminateSocket(clientSocket);
      return;
    }

    int trasmitAttemptCount = 0;
    boolean recievedResponse = false;
    DatagramPacket recievedPacket =
        new DatagramPacket(new byte[MAX_PACKET_LENGTH], MAX_PACKET_LENGTH);
    do {
      trasmitAttemptCount++;
      try {
        clientSocket.receive(recievedPacket);
        if (!recievedPacket.getAddress().equals(server)) {
          throw new IOException("Received packet from an unknown source");
        }
      } catch (SocketTimeoutException e) {
        try {
          clientSocket.send(toSend);
        } catch (IOException e1) {
          System.err.println("Communication problem: send");
          terminateSocket(clientSocket);
          return;
        }
        continue;
      } catch (IOException e) {
        System.err.println("Communication problem: unknown");
        terminateSocket(clientSocket);
        return;
      }

      Message recievedMessage;
      try {
        recievedMessage =
            Message.decode(
                Arrays.copyOfRange(recievedPacket.getData(), 0, recievedPacket.getLength()));
      } catch (NullPointerException | IllegalArgumentException e) {
        System.err.println("Invalid message: decode receive " + e.getMessage());
        continue;
      }

      switch (recievedMessage.getOp()) {
        case QUERY:
          System.err.println("Unexpected message type");
          continue;
        case NEW:
          System.err.println("Unexpected message type");
          continue;
        case ERROR:
          System.err.println(
              "Error: " + ((bettercom.jack.serialization.Error) recievedMessage).getErrorMessage());
          terminateSocket(clientSocket);
          return;
        case RESPONSE:
          if (msgToSend.getOp() == JackMessageOpType.QUERY) {
            System.out.println("Recieved: " + recievedMessage);
            recievedResponse = true;
            break;
          } else {
            System.err.println("Unexpected message type");
            continue;
          }
        case ACK_NEW:
          if (msgToSend.getOp() == JackMessageOpType.NEW) {
            if (msgToSend.generatePayload().equals(recievedMessage.generatePayload())) {
              System.out.println("Recieved: " + recievedMessage);
              recievedResponse = true;
              break;
            } else {
              System.err.println("Unexpected ACK");
              continue;
            }
          } else {
            System.err.println("Unexpected message type");
            continue;
          }
        default:
          System.err.println("Invalid message: switch op");
          continue;
      }

    } while ((!recievedResponse) && (trasmitAttemptCount < MAX_RETRY));

    if (trasmitAttemptCount >= MAX_RETRY) {
      System.err.println("No response after 3 retransmissions");
    }
    terminateSocket(clientSocket);
  }
Ejemplo n.º 19
0
  public Connector(String endpoint) throws SocketException, UnknownHostException {
    InetAddress ep = InetAddress.getByName(endpoint);
    socket = new DatagramSocket();
    socket.connect(ep, CONNECTIONPORT);
    this.endpoint = endpoint;

    pendingRes = new HashMap<Integer, ResponsePayload>();
    rand = new Random();
    identifierPool = new ArrayList<Integer>();

    Runnable s =
        new Runnable() {
          @Override
          public void run() {
            boolean connection = true;
            while (connection) {
              try {
                byte[] buf = new byte[4096];
                DatagramPacket rp = new DatagramPacket(buf, buf.length);
                socket.receive(rp);

                if ((new String(buf, 0, 4)).equals("a000")) {
                  continue;
                }

                String s = new String(buf, 0, rp.getLength());

                Log.d("AUDIO_DEBUGGING", "Data received: " + s);
                try {
                  NotifyPayload notifyPayload = NotifyPayload.Deserialize(s);

                  if (notifyPayload.status.equals("notify")) {
                    setChanged();
                    notifyObservers(notifyPayload);
                  }

                } catch (Exception e) {

                }
                try {
                  ResponsePayload responsePayload = ResponsePayload.Deserialize(s);

                  int identity = responsePayload.identity;
                  removeIdentity(identity);

                  if (identity != 0 && pendingRes.containsKey(identity)) {
                    pendingRes.put(identity, responsePayload);
                  }
                } catch (Exception e) {

                }
              } catch (SocketException e) {
                connection = false;
              } catch (IOException e) {
                connection = false;
              }
            }
          }
        };
    new Thread(s).start();
  }