Ejemplo n.º 1
0
  // Check if the datagramsocket adaptor can send with a packet
  // that has not been initialized with an address; the legacy
  // datagram socket will send in this case
  private static void test2() throws Exception {
    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    byte b[] = "hello".getBytes("UTF-8");
    DatagramPacket pkt = new DatagramPacket(b, b.length);
    sndChannel.socket().send(pkt);

    ByteBuffer bb = ByteBuffer.allocate(256);
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    // Check that the pkt got set with the target address;
    // This is legacy behavior
    if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Ejemplo n.º 2
0
  // Check if DatagramChannel.send while connected can include
  // address without throwing
  private static void test1() throws Exception {

    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    ByteBuffer bb = ByteBuffer.allocate(256);
    bb.put("hello".getBytes());
    bb.flip();
    int sent = sndChannel.send(bb, receiver);
    bb.clear();
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Ejemplo n.º 3
0
 public byte[] getRAddr() {
   try {
     InetAddress addr = InetAddress.getByName(host);
     return addr.getAddress();
   } catch (UnknownHostException e) {
     System.err.println("NCCPConnection::getRAddr Don't know about host: ");
     return null;
   }
 }
Ejemplo n.º 4
0
 Target(String host) {
   try {
     address = new InetSocketAddress(InetAddress.getByName(host), 80);
   } catch (IOException x) {
     failure = x;
   }
 }
Ejemplo n.º 5
0
  /**
   * Checks if address can be reached using one argument InetAddress.isReachable() version or ping
   * command if failed.
   *
   * @param addr Address to check.
   * @param reachTimeout Timeout for the check.
   * @return {@code True} if address is reachable.
   */
  public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
      if (addr.isReachable(reachTimeout)) return true;

      String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

      Process myProc = Runtime.getRuntime().exec(cmd);

      myProc.waitFor();

      return myProc.exitValue() == 0;
    } catch (IOException ignore) {
      return false;
    } catch (InterruptedException ignored) {
      Thread.currentThread().interrupt();

      return false;
    }
  }
Ejemplo n.º 6
0
  public static void setup() throws Exception {
    client = DatagramChannel.open();
    server = DatagramChannel.open();

    client.socket().bind((SocketAddress) null);
    server.socket().bind((SocketAddress) null);

    client.configureBlocking(false);
    server.configureBlocking(false);

    InetAddress address = InetAddress.getLocalHost();
    int port = client.socket().getLocalPort();
    isa = new InetSocketAddress(address, port);
  }
Ejemplo n.º 7
0
  static void test() throws Exception {
    ServerSocketChannel ssc = null;
    SocketChannel sc = null;
    SocketChannel peer = null;
    try {
      ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));

      // loopback connection
      InetAddress lh = InetAddress.getLocalHost();
      sc = SocketChannel.open(new InetSocketAddress(lh, ssc.socket().getLocalPort()));
      peer = ssc.accept();

      // peer sends message so that "sc" will be readable
      int n = peer.write(ByteBuffer.wrap("Hello".getBytes()));
      assert n > 0;

      sc.configureBlocking(false);

      Selector selector = Selector.open();
      SelectionKey key = sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

      boolean done = false;
      int failCount = 0;
      while (!done) {
        int nSelected = selector.select();
        if (nSelected > 0) {
          if (nSelected > 1) throw new RuntimeException("More than one channel selected");
          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> iterator = keys.iterator();
          while (iterator.hasNext()) {
            key = iterator.next();
            iterator.remove();
            if (key.isWritable()) {
              failCount++;
              if (failCount > 10) throw new RuntimeException("Test failed");
              Thread.sleep(250);
            }
            if (key.isReadable()) {
              done = true;
            }
          }
        }
      }
    } finally {
      if (peer != null) peer.close();
      if (sc != null) sc.close();
      if (ssc != null) ssc.close();
    }
  }
Ejemplo n.º 8
0
  private void init() throws IOException {
    messageBuffer = new ArrayList();
    receiveBuffer = ByteBuffer.allocate(CAPACITY);
    sendBuffer = ByteBuffer.allocate(CAPACITY);
    buf = new byte[CAPACITY];

    channel = DatagramChannel.open();
    channel.configureBlocking(false);

    InetAddress host = null;
    if (getAddress() != null) {
      host = InetAddress.getByAddress(getAddress().getBytes());
    }
    channel.socket().bind(new InetSocketAddress(host, getPort()));
    channel.socket().setReceiveBufferSize(CAPACITY);

    certifier = new MessageCertifier(this);
    extractor = new MessageExtractor(this);
  }
 /**
  * Creates a default TCP transport mapping with the server for incoming messages disabled.
  *
  * @throws UnknownHostException
  * @throws IOException on failure of binding a local port.
  */
 public DefaultTcpTransportMapping() throws UnknownHostException, IOException {
   super(new TcpAddress(InetAddress.getLocalHost(), 0));
 }
Ejemplo n.º 10
0
  public static void main(String[] args) throws Exception {
    //////////////////// STAGE A//////////////////////////////////////////
    int portNum = 12235;
    //        InetAddress ip=InetAddress.getLocalHost();
    InetAddress ip = InetAddress.getByName("attu2.cs.washington.edu");

    DatagramSocket sock = new DatagramSocket();

    byte[] response = new byte[HEADER_SIZE + 16];
    String partA = "hello world\0";
    byte[] buf = createBuffer(partA.getBytes(), 0, STEP1);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, portNum);
    sock.send(packet);
    packet = new DatagramPacket(response, response.length);
    sock.receive(packet);
    int[] a2 = partA(response); // putting the 4 ints from server into int[]

    //      for (int i = 0; i < a2.length; i++) {
    //          System.out.println(a2[i]);
    //      }

    ////////////////////// STAGE B////////////////////////////////////////

    int numSent = 0;
    int send = a2[0];
    int len = a2[1];
    portNum = a2[2];
    int secretA = a2[3];
    System.out.println("The secrets:\nA: " + secretA);

    sock.setSoTimeout(500); // .5s

    while (numSent < send) {
      // create packet
      buf = createBuffer(partB(numSent, len), secretA, STEP1);
      packet = new DatagramPacket(buf, buf.length, ip, portNum);
      sock.send(packet);
      // send packet
      try {
        sock.receive(new DatagramPacket(response, response.length));
        numSent++;
        ByteBuffer temp = ByteBuffer.wrap(response);
        checkHeader(temp, 4, secretA, STEP1);
        //              System.out.println(temp.getInt());  // For debug. See if counts up by 1
      } catch (SocketTimeoutException e) {
        // if there's a timeout, try again
        continue;
      }
    }
    response = new byte[HEADER_SIZE + 8]; // 8 bytes -- 2 integers
    sock.receive(new DatagramPacket(response, response.length));
    ByteBuffer bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 8, secretA, STEP2);

    // reset the port number to the one given
    portNum = bb.getInt();
    int secretB = bb.getInt();
    System.out.println("B: " + secretB);

    // close the UDP socket
    sock.close();

    /////////////////////////// STAGE C///////////////////////////////////
    Socket socket = new Socket(ip, portNum);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    response = new byte[HEADER_SIZE + 16]; // 4 ints given to us this time
    in.read(response);
    bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 13, secretB, STEP2);

    // num2 len2 secretC and char c

    numSent = bb.getInt();
    len = bb.getInt();
    int secretC = bb.getInt();
    System.out.println("C: " + secretC);

    // stage d
    byte c = (byte) bb.getChar();
    buf = new byte[len];
    Arrays.fill(buf, c);
    for (int i = 0; i < numSent; i++) {
      byte[] b = createBuffer(buf, secretC, STEP1);
      out.write(b);
    }
    response = new byte[12 + 4]; // one integer. secretD plus header
    in.read(response);
    bb = ByteBuffer.wrap(response);
    checkHeader(bb, 4, secretC, STEP2);

    int secretD = bb.getInt();
    socket.close();
    in.close();
    out.close();
    System.out.println("D: " + secretD);
  }