Exemplo n.º 1
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;
    }
  }
  /**
   * 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;
  }