public void execute() throws BuildException {
    try {
      InetAddress localHost = InetAddress.getLocalHost();

      if (Validator.isNotNull(_hostAddressProperty)) {
        getProject().setUserProperty(_hostAddressProperty, localHost.getHostAddress());
      }

      if (Validator.isNotNull(_hostNameProperty)) {
        getProject().setUserProperty(_hostNameProperty, localHost.getHostName());
      }

      if (Validator.isNotNull(_vmId1Property)) {
        int id = GetterUtil.getInteger(StringUtil.extractDigits(localHost.getHostName()));

        getProject().setUserProperty(_vmId1Property, String.valueOf((id * 2) - 1));
      }

      if (Validator.isNotNull(_vmId2Property)) {
        int id = GetterUtil.getInteger(StringUtil.extractDigits(localHost.getHostName()));

        getProject().setUserProperty(_vmId2Property, String.valueOf((id * 2)));
      }
    } catch (UnknownHostException uhe) {
      throw new BuildException(uhe);
    }
  }
 @Override
 public void run() {
   Log.i(TAG, "Server " + addr.getHostName() + " started");
   while (true) {
     try {
       Socket socket = serverSocket.accept();
       int flag = socket.getInputStream().read();
       if (flag == FLAG_REQUEST) {
         DataInputStream in = new DataInputStream(socket.getInputStream());
         String text = in.readUTF();
         Log.i(TAG, text);
         playText(text, service);
         in.close();
       } else if (flag == FLAG_STOP_ALL) {
         Log.i(
             TAG, "Detected \"stop all\" signal from " + socket.getInetAddress().getHostName());
         for (ServerThread st : serverThreads) {
           st.stop();
         }
         break;
       }
     } catch (IOException ex) {
       Log.e(TAG, "", ex);
     }
   }
   Log.i(TAG, "Server " + addr.getHostName() + " finished");
   if (!destroyed) {
     stop();
   }
 }
示例#3
0
  /**
   * Converts collection of rich nodes to block location data.
   *
   * @param nodes Collection of affinity nodes.
   */
  private void convertFromNodes(Collection<ClusterNode> nodes) {
    Collection<String> names = new LinkedHashSet<>();
    Collection<String> hosts = new LinkedHashSet<>();
    Collection<UUID> nodeIds = new ArrayList<>(nodes.size());

    for (final ClusterNode node : nodes) {
      // Normalize host names into Hadoop-expected format.
      try {
        Collection<InetAddress> addrs = U.toInetAddresses(node);

        for (InetAddress addr : addrs) {
          if (addr.getHostName() == null) names.add(addr.getHostAddress() + ":" + 9001);
          else {
            names.add(addr.getHostName() + ":" + 9001); // hostname:portNumber
            hosts.add(addr.getHostName());
          }
        }
      } catch (IgniteCheckedException ignored) {
        names.addAll(node.addresses());
      }

      nodeIds.add(node.id());
    }

    this.nodeIds = nodeIds;
    this.names = names;
    this.hosts = hosts;
  }
  /**
   * Retrieves an array of Strings naming the distinct, known to be valid local InetAddress names
   * for this machine. The process is to collect and return the union of the following sets:
   *
   * <ol>
   *   <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress())
   *   <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostName())
   *   <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostAddress())
   *   <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostName())
   *   <li>InetAddress.getByName("loopback").getHostAddress()
   *   <li>InetAddress.getByName("loopback").getHostname()
   * </ol>
   *
   * @return the distinct, known to be valid local InetAddress names for this machine
   */
  public static String[] listLocalInetAddressNames() {

    InetAddress addr;
    InetAddress[] addrs;
    HashSet set;

    set = new HashSet();

    try {
      addr = InetAddress.getLocalHost();
      addrs = InetAddress.getAllByName(addr.getHostAddress());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }

      addrs = InetAddress.getAllByName(addr.getHostName());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }
    } catch (Exception e) {
    }

    try {
      addr = InetAddress.getByName(null);
      addrs = InetAddress.getAllByName(addr.getHostAddress());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }

      addrs = InetAddress.getAllByName(addr.getHostName());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }
    } catch (Exception e) {
    }

    try {
      set.add(InetAddress.getByName("loopback").getHostAddress());
      set.add(InetAddress.getByName("loopback").getHostName());
    } catch (Exception e) {
    }

    return (String[]) set.toArray(new String[set.size()]);
  }
示例#5
0
 /**
  * @param address IP address to bind
  * @param dns JmDNS instance
  * @param jmdnsName JmDNS name
  * @return new HostInfo
  */
 public static HostInfo newHostInfo(InetAddress address, JmDNSImpl dns, String jmdnsName) {
   HostInfo localhost = null;
   String aName = "";
   InetAddress addr = address;
   try {
     if (addr == null) {
       String ip = System.getProperty("net.mdns.interface");
       if (ip != null) {
         addr = InetAddress.getByName(ip);
       } else {
         addr = InetAddress.getLocalHost();
         if (addr.isLoopbackAddress()) {
           // Find local address that isn't a loopback address
           InetAddress[] addresses =
               NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
           if (addresses.length > 0) {
             addr = addresses[0];
           }
         }
       }
       aName = addr.getHostName();
       if (addr.isLoopbackAddress()) {
         logger.warning("Could not find any address beside the loopback.");
       }
     } else {
       aName = addr.getHostName();
     }
     if (aName.contains("in-addr.arpa") || (aName.equals(addr.getHostAddress()))) {
       aName =
           ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : addr.getHostAddress());
     }
   } catch (final IOException e) {
     logger.log(
         Level.WARNING,
         "Could not intialize the host network interface on "
             + address
             + "because of an error: "
             + e.getMessage(),
         e);
     // This is only used for running unit test on Debian / Ubuntu
     addr = loopbackAddress();
     aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : "computer");
   }
   // A host name with "." is illegal. so strip off everything and append .local.
   aName = aName.replace('.', '-');
   aName += ".local.";
   localhost = new HostInfo(addr, aName, dns);
   return localhost;
 }
示例#6
0
  static {
    try {

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

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

      TotalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    } catch (Exception e) {
      System.out.println("获取系统信息失败");
      e.printStackTrace();
    }
  }
  /**
   * Determine the hostname of the machine Kettle is running on
   *
   * @return The hostname
   */
  public static final String getHostname() {
    String lastHostname = "localhost";
    try {
      Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
      while (en.hasMoreElements()) {
        NetworkInterface nwi = en.nextElement();
        Enumeration<InetAddress> ip = nwi.getInetAddresses();

        while (ip.hasMoreElements()) {
          InetAddress in = (InetAddress) ip.nextElement();
          lastHostname = in.getHostName();
          // System.out.println("  ip address bound : "+in.getHostAddress());
          // System.out.println("  hostname         : "+in.getHostName());
          // System.out.println("  Cann.hostname    : "+in.getCanonicalHostName());
          // System.out.println("  ip string        : "+in.toString());
          if (!lastHostname.equalsIgnoreCase("localhost") && !(lastHostname.indexOf(':') >= 0)) {
            return lastHostname;
          }
        }
      }
    } catch (SocketException e) {

    }

    return lastHostname;
  }
示例#8
0
 public ActivityTagFactory() {
   String userinfo = System.getProperty("user.name");
   if (userinfo != null) {
     userinfo = userinfo.replaceAll("^[^a-zA-Z0-9.-]+", "");
     userinfo = userinfo.replaceAll("[^a-zA-Z0-9.-]+$", "");
     userinfo = userinfo.replaceAll("[^a-zA-Z0-9.-]", "_");
   }
   if (userinfo == null || userinfo.length() == 0) {
     userinfo = "";
   } else {
     userinfo = userinfo + "@";
   }
   String authority = "localhost";
   try {
     InetAddress localMachine = InetAddress.getLocalHost();
     authority = localMachine.getHostName();
     authority = authority.replaceAll("^[^a-zA-Z0-9.-]+", "");
     authority = authority.replaceAll("[^a-zA-Z0-9.-]+$", "");
     authority = authority.replaceAll("[^a-zA-Z0-9.-]", "_");
     authority = authority.toLowerCase();
   } catch (UnknownHostException e) {
     // ignore
   }
   space = "tag:" + userinfo + authority + ",";
 }
示例#9
0
  public static void main(String[] args) throws UnknownHostException {
    // 获取本机的InetAddress实例
    InetAddress address = InetAddress.getLocalHost();
    System.out.println("计算名:" + address.getHostName());
    System.out.println("IP地址:" + address.getHostAddress());
    byte[] bytes = address.getAddress(); // 获取字节数组形式的IP地址
    System.out.println("字节数组形式的IP:" + Arrays.toString(bytes));
    System.out.println(address); // 直接输出InetAddress对象

    // 根据机器名获取InetAddress实例
    // InetAddress address2=InetAddress.getByName("wyf-PC");//1
    InetAddress address2 = InetAddress.getByName("111.111.113.23"); // 2
    //		1和2都行
    System.out.println("计算名:" + address2.getHostName());
    System.out.println("IP地址:" + address2.getHostAddress());
  }
示例#10
0
  public static final Map<String, List<InetAddress>> listHostAddresses() {
    Map<String, List<InetAddress>> result = new HashMap<String, List<InetAddress>>();
    try {
      Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
      while (ifs.hasMoreElements()) {
        NetworkInterface iface = ifs.nextElement();
        if (iface.isUp() && !iface.isPointToPoint()) {
          Enumeration<InetAddress> addrs = iface.getInetAddresses();
          while (addrs.hasMoreElements()) {
            InetAddress addr = addrs.nextElement();

            String hostName = addr.getHostName();

            if (!hostName.equals(addr.getHostAddress())) {
              // only take interfaces with a proper hostname configured

              List<InetAddress> addresses = result.get(hostName);
              if (addresses == null) {
                addresses = new ArrayList<InetAddress>();
                result.put(hostName, addresses);
              }
              addresses.add(addr);
            }
          }
        }
      }
      return result;
    } catch (SocketException ex) {
      log.warn("could not determine local IP addresses, will use localhost only");
      return Collections.emptyMap();
    }
  }
示例#11
0
  public static int getID() {
    int id = -1;
    try {
      InetAddress local = InetAddress.getLocalHost();
      String hostname = local.getHostName();

      InetAddress[] all = InetAddress.getAllByName(hostname);
      for (int i = 0; i < all.length; i++) {
        String ip = all[i].getHostAddress();
        System.out.println(i + ": " + all[i].getHostName() + " " + ip);
        if (ip.indexOf("192") > -1) {
          String sid = ip.substring(ip.length() - 1, ip.length());
          id = Integer.parseInt(sid);
          System.out.println("Found the ID: " + id);
        }
      }

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

    if (id < 0) {
      System.out.println("IP Address not detected properly");
    }

    return id;
  }
示例#12
0
 @Override
 protected void populateLocalName() {
   InetAddress inetAddr = getSocket().getIOChannel().socket().getLocalAddress();
   if (inetAddr != null) {
     localName = inetAddr.getHostName();
   }
 }
示例#13
0
 /**
  * Creates a {@link TcpConnectionSupport} object and publishes a {@link TcpConnectionEvent} with
  * {@link TcpConnectionEventType#OPEN}, if so configured.
  *
  * @param socket the underlying socket.
  * @param server true if this connection is a server connection
  * @param lookupHost true if reverse lookup of the host name should be performed, otherwise, the
  *     ip address will be used for identification purposes.
  * @param applicationEventPublisher the publisher to which OPEN, CLOSE and EXCEPTION events will
  *     be sent; may be null if event publishing is not required.
  * @param connectionFactoryName the name of the connection factory creating this connection; used
  *     during event publishing, may be null, in which case "unknown" will be used.
  */
 public TcpConnectionSupport(
     Socket socket,
     boolean server,
     boolean lookupHost,
     ConnectionFactorySupport<T> connectionFactory) {
   this.connectionFactory = connectionFactory;
   this.server = server;
   InetAddress inetAddress = socket.getInetAddress();
   if (inetAddress != null) {
     this.hostAddress = inetAddress.getHostAddress();
     if (lookupHost) {
       this.hostName = inetAddress.getHostName();
     } else {
       this.hostName = this.hostAddress;
     }
   }
   int port = socket.getPort();
   this.connectionId = this.hostName + ":" + port + ":" + UUID.randomUUID().toString();
   if (connectionFactoryName != null) {
     this.connectionFactoryName = connectionFactoryName;
   }
   if (logger.isDebugEnabled()) {
     logger.debug("New connection " + this);
   }
 }
 public static void main(String[] arg) {
   List<InetAddress> list = ServiceDiscoveryClient.discoverService();
   for (InetAddress l : list) {
     System.out.println(l.getHostAddress());
     System.out.println(l.getHostName());
   }
 }
  @Override
  public void setAddress(InetAddress address) {
    if (log.isDebugEnabled())
      log.debug("Address is {}:{}", address.getHostName(), address.getHostAddress());

    this.address = address;
  }
  /**
   * Returns true if DAS and remote server is running in the same machine. This allows to perform
   * same host optimization during zip download.
   *
   * @return true if DAS and remote server runs on the same machine
   */
  private boolean isSameHost() {

    boolean tf = false;

    String dasZipLoc = _response.getZipLocation();
    File zip = new File(dasZipLoc);

    // the zip file name after the time stamp exists in the remote
    // server instance
    if (zip.exists()) {
      long dasLastModified = _response.getLastModifiedOfZip();
      long localLastModified = zip.lastModified();

      // last modified of zip is the same
      if (dasLastModified == localLastModified) {

        // host name of DAS
        String dasHostName = _response.getDasHostName();
        try {
          InetAddress host = InetAddress.getLocalHost();
          // host name of DAS is same is this server instance
          if ((dasHostName != null) && (dasHostName.equals(host.getHostName()))) {

            tf = true;
          }
        } catch (UnknownHostException uhe) {
          // ignore
        }
      }
    }

    return tf;
  }
 @Override
 public void execute() throws MojoExecutionException, MojoFailureException {
   if (skip) {
     getLog().debug(String.format("Skipping add-resource with address %s", address));
     return;
   }
   try {
     final InetAddress host = getHostAddress();
     getLog()
         .info(
             String.format(
                 "Executing goal %s on server %s (%s) port %s.",
                 goal(), host.getHostName(), host.getHostAddress(), getPort()));
     synchronized (CLIENT_LOCK) {
       final ModelControllerClient client = getClient();
       if (resources != null && resources.length > 0) {
         processResources(client, resources);
       } else {
         getLog().warn("No resources were provided.");
       }
     }
   } catch (Exception e) {
     throw new MojoExecutionException(
         String.format("Could not execute goal %s. Reason: %s", goal(), e.getMessage()), e);
   } finally {
     close();
   }
 }
示例#18
0
  public static void comoClienteDelServidorCentral(String ip, int puerto) {
    try {
      Socket cliente = new Socket(ip, puerto); // crea socket con ip y puerto
      PrintWriter salida = new PrintWriter(cliente.getOutputStream(), true);
      BufferedReader entrada = new BufferedReader(new InputStreamReader(cliente.getInputStream()));

      InetAddress address = InetAddress.getLocalHost();
      System.out.println(address);
      String nombreMaquinaCliente = address.getHostName();
      String ipCliente = address.getHostAddress();

      salida.println(
          "Cliente conectando, nombre: " + nombreMaquinaCliente + " direccionIP: " + ipCliente);
      String puertoNuevo = entrada.readLine();
      System.out.println(" resp:" + puertoNuevo);
      int puertoNuevoEntero = Integer.parseInt(puertoNuevo);

      salida.close();
      entrada.close();
      cliente.close();

      Socket cliente2 = new Socket(ip, puertoNuevoEntero); // crea socket con ip y puerto
      PrintWriter salida2 = new PrintWriter(cliente2.getOutputStream(), true);
      BufferedReader entrada2 =
          new BufferedReader(new InputStreamReader(cliente2.getInputStream()));

      salida2.println("nuevaConexion papi: " + address);
      System.out.println(entrada2.readLine());

    } catch (Exception e) {
      System.out.println("Problemas al enviar el mensaje");
      e.printStackTrace();
    }
  }
 @Test
 public void testGetPlatformHostPortConstructorTrue() {
   // uses hostName and port
   SystemHostPlatformSelector selector = new SystemHostPlatformSelector(true, 80);
   String platform = selector.getPlatformIdentifier();
   Assert.assertEquals(address.getHostName() + ":80", platform);
 }
  /**
   * Gives a status report of the request.
   *
   * @return The status report of the request.
   */
  public synchronized String toString() {
    StringBuffer s = new StringBuffer(300);
    s.append(tostring());
    s.append("\nPeer/Port : " + address.getHostName() + "/" + port);

    return s.toString();
  }
  /**
   * Initializes the Graphite reporter based on the current configuration.
   *
   * @param config the graphite reporter configuration
   */
  private void configureGraphiteReporter(GraphiteReporterConfig config) {
    if (config.isEnabled()) {
      Graphite graphite =
          new Graphite(new InetSocketAddress(config.getServerUri(), config.getServerPort()));

      String nodeName;

      try {
        InetAddress localhost = InetAddress.getLocalHost();
        nodeName = localhost.getHostName();
      } catch (UnknownHostException e) {
        nodeName = "UNKNOWN";
      }

      graphiteReporter =
          GraphiteReporter.forRegistry(metricRegistry)
              .prefixedWith(String.format("motech.%s", nodeName))
              .convertRatesTo(config.getConvertRates())
              .convertDurationsTo(config.getConvertDurations())
              .filter(MetricFilter.ALL)
              .build(graphite);

      graphiteReporter.start(config.getFrequency(), config.getFrequencyUnit());
    }
  }
示例#22
0
  void register(String hostName, final int rmiPort, final int serverPort) {

    try {
      final ManagementImpl impl = (ManagementImpl) _persistit.getManagement();
      if (hostName == null && rmiPort != -1) {
        try {
          if (hostName == null) {
            final InetAddress addr = InetAddress.getLocalHost();
            try {
              hostName = addr.getHostName() + ":" + rmiPort;
            } catch (final Exception e) {
              hostName = addr.getHostAddress() + ":" + rmiPort;
            }
          }
        } catch (final NumberFormatException nfe) {
        }
      }
      if (rmiPort != -1 && _localRegistryPort != rmiPort) {
        LocateRegistry.createRegistry(rmiPort);
        _localRegistryPort = rmiPort;
      }

      if (hostName != null && hostName.length() > 0) {
        final String name = "//" + hostName + "/PersistitManagementServer";
        UnicastRemoteObject.exportObject(impl, serverPort);
        Naming.rebind(name, impl);
        impl._registered = true;
        impl._registeredHostName = hostName;
        _persistit.getLogBase().rmiServerRegistered.log(hostName);
      }
    } catch (final Exception exception) {
      _persistit.getLogBase().rmiRegisterException.log(hostName, exception);
    }
  }
示例#23
0
 public String getLocalHostName() {
   try {
     return InetAddress.getLocalHost().getHostName();
   } catch (UnknownHostException e) {
     return m_local.getHostName();
   }
 }
  /**
   * Method that adds the HTTP protocol to a request message
   *
   * @param data Request message to add HTTP protocol to
   * @param url Tag/URL to add to message
   * @return the request with the HTTP protocol added
   * @exception context.arch.comm.protocol.ProtocolException if the protocol can not be added
   */
  public String addRequestProtocol(String data, String url, String type) throws ProtocolException {
    int xmlLen = data.length();
    String eol = "\r\n";
    StringBuffer text = new StringBuffer();
    String thisMachine;
    try { // get our machine name
      InetAddress thisInet = InetAddress.getLocalHost();
      thisMachine = thisInet.getHostName();
    } catch (UnknownHostException e) {
      thisMachine = "localhost";
    }

    xmlLen += 2 * eol.length(); // add length of end of lines at the end
    if (type.equals(POST)) {
      text.append(POST + " " + url + " HTTP/1.0" + eol);
    } else {
      text.append(GET + " " + url + " HTTP/1.0" + eol);
    }
    text.append("User-Agent: Context Client" + eol);
    text.append("Host: " + thisMachine + eol);
    if (type.equals(POST)) {
      text.append("Content-Type: text/xml" + eol);
      text.append("Content-Length: " + xmlLen + eol);
      text.append(eol);
      text.append(data + eol);
    }
    text.append(eol);
    // commObject.println("\nHTTPClientSocket : addRequestProtocol\n" + " CONTENT:\n" +
    // text.toString());
    return text.toString();
  }
示例#25
0
    @Override
    protected Void doInBackground(Void... params) {

      try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {

          NetworkInterface thisInterface = networkInterfaces.nextElement();
          Enumeration<InetAddress> inetAddresses = thisInterface.getInetAddresses();
          if (inetAddresses.hasMoreElements()) {
            String niInfo = thisInterface.getDisplayName() + "\n";

            while (inetAddresses.hasMoreElements()) {
              InetAddress thisAddress = inetAddresses.nextElement();
              niInfo += "---\n";
              niInfo += "Address: " + thisAddress.getAddress() + "\n";
              niInfo += "CanonicalHostName: " + thisAddress.getCanonicalHostName() + "\n";
              niInfo += "HostAddress: " + thisAddress.getHostAddress() + "\n";
              niInfo += "HostName: " + thisAddress.getHostName() + "\n";
            }

            publishProgress(niInfo);
          }
        }
      } catch (SocketException e) {
        e.printStackTrace();
      }
      return null;
    }
示例#26
0
  public static void main(String args[]) throws UnknownHostException {

    InetAddress address = InetAddress.getLocalHost();

    System.out.println("locla address----->" + address.getHostAddress());
    System.out.println("local host name----->" + address.getHostName());
  }
  /** Creates the server. */
  public static void main(String args[]) {
    client = null;
    ServerSocket server = null;

    try {
      System.out.print("\nCreating Server...\n");
      // creates the server
      server = new ServerSocket(8008);
      System.out.print("Created\n");
      // get the ip Address and the host name.
      InetAddress localAddr = InetAddress.getLocalHost();
      System.out.println("IP address: " + localAddr.getHostAddress());
      System.out.println("Hostname: " + localAddr.getHostName());

    } catch (IOException e) {
      // sends a
      System.out.println("IO" + e);
    }

    // constantly checks for a new aocket trying to attach itself to the trhead
    while (true) {
      try {
        client = server.accept();
        // create a new thread.
        FinalMultiThread thr = new FinalMultiThread(client);
        System.out.print(client.getInetAddress() + " : " + thr.getUserName() + "\n");
        CliList.add(thr);
        current++;
        thr.start();
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
示例#28
0
  private synchronized void initializeHostCache() {
    if (!initialized) {
      // first, add the known interfaces. This is the only safe method to get
      // the _real_ IP addresses, and get _all_ of them.
      addLocalAddressesByInterface();
      try {
        // Add what Java thinks is the local host.
        InetAddress localHostJava = InetAddress.getLocalHost();
        // Do _not_ add the address that Java thinks the local host has,
        // since it may be wrong! This is due to the method Java uses:
        // it takes the host _name_ and does a reverse name lookup
        // to get the address. This may be _wrong_ in case the DNS server
        // points to a different (or outdated) address for the name.
        // In reality, _only_ the addresses given by our own interfaces
        // are correct! (As obtained by addLocalAddressesByInterface()).
        // addLocalAddress(localHostJava);

        // Add what Java thinks is the local host name.
        // The local host name correct in the sense that it is configured
        // locally and thus known locally. Note that in case of DNS inconsistency,
        // DNS servers will return a _different_ address for the name than the
        // local one, in this case the host name will be added as non-local.
        addHostName(localHostJava.getHostName());
      } catch (UnknownHostException e) {
        /* no error */
      }
      // finally, add the "localhost" special host name since it might not be covered
      // by the methods above (we cannot get all names for a given address, only the other way
      // round).
      addHostName("localhost"); // $NON-NLS-1$
      // mark as initialized
      initialized = true;
    }
  }
示例#29
0
  /**
   * Add a standardised amount of information about an interface. This is in the form:
   *
   * <pre>
   *     [interfaces]
   *       |
   *       |
   *       +--[ id ] (branch)
   *       |   |
   *       |   +-- "order"  (integer metric: 1 .. 2 ..)
   *       |   +-- "FQDN" (string metric: the host's FQDN, as presented by the door)
   *       |   +-- "address" (string metric: the host's address; e.g., "127.0.0.1")
   *       |   +-- "address-type"    (string metric: "IPv4", "IPv6" or "unknown")
   *       |   +-- "scope"    (string metric: "IPv4", "IPv6" or "unknown")
   *       |
   * </pre>
   *
   * @param update The StateUpdate to append the new metrics.
   * @param parentPath the path that the id branch will be added.
   * @param lifetime how long the created metrics should last.
   */
  private void addInterfaceInfo(
      StateUpdate update, StatePath parentPath, InetAddress address, long lifetime) {
    StatePath pathToInterfaceBranch = parentPath.newChild(address.getHostAddress());

    String hostName = address.getHostName();
    update.appendUpdate(
        pathToInterfaceBranch.newChild("FQDN"), new StringStateValue(hostName, lifetime));

    String urlName = (isInetAddress(hostName)) ? toUriString(address) : hostName;
    update.appendUpdate(
        pathToInterfaceBranch.newChild("url-name"), new StringStateValue(urlName, lifetime));

    update.appendUpdate(
        pathToInterfaceBranch.newChild("address"),
        new StringStateValue(address.getHostAddress(), lifetime));
    update.appendUpdate(
        pathToInterfaceBranch.newChild("address-type"),
        new StringStateValue(
            (address instanceof Inet4Address)
                ? "IPv4"
                : (address instanceof Inet6Address) ? "IPv6" : "unknown",
            lifetime));
    update.appendUpdate(
        pathToInterfaceBranch.newChild("scope"),
        new StringStateValue(NetworkUtils.InetAddressScope.of(address).toString().toLowerCase()));
  }
示例#30
0
  public static void main(String[] args) {
    if (args.length == 0) {
      System.err.println("Usage: ntp.NTPClient <hostname-or-address-list>");
      System.exit(1);
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
      client.open();
      for (String arg : args) {
        System.out.println();
        try {
          InetAddress hostAddr = InetAddress.getByName(arg);
          System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
          TimeInfo info = client.getTime(hostAddr);
          processResponse(info);
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }

    client.close();
  }