Esempio n. 1
0
  public static void main(String[] args) throws Exception {
    InetAddress ip = InetAddress.getByName("www.baidu.com");
    System.out.println("baidu是否可达:" + ip.isReachable(2000));
    System.out.println(ip.getHostAddress());

    InetAddress local = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
    System.out.println("本机是否可达:" + local.isReachable(5000));
    System.out.println(local.getCanonicalHostName());
  }
Esempio n. 2
0
 public static void main(String[] args) throws Exception {
   // 根据主机名来获取对应的InetAddress实例
   InetAddress ip = InetAddress.getByName("www.oneedu.cn");
   // 判断是否可达
   System.out.println("oneedu是否可达:" + ip.isReachable(2000));
   // 获取该InetAddress实例的IP字符串
   System.out.println(ip.getHostAddress());
   // 根据原始IP地址来获取对应的InetAddress实例
   InetAddress local = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
   System.out.println("本机是否可达:" + local.isReachable(5000));
   // 获取该InetAddress实例对应的全限定域名
   System.out.println(local.getCanonicalHostName());
 }
 /**
  * A function to test the connection
  *
  * @throws UnknownHostException
  * @throws IOException
  */
 public void testConnection() throws UnknownHostException, IOException {
   InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
   for (InetAddress address : addresses) {
     if (address.isReachable(timeout)) System.out.printf("%s is reachable%n", address);
     else System.out.printf("%s could not be contacted%n", address);
   }
 }
  private NetworkInterface GetExternalNetworkInterface() {
    try {
      // iterate over the network interfaces known to java
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      OUTER:
      for (NetworkInterface interface_ : Collections.list(interfaces)) {
        // we shouldn't care about loopback addresses
        if (interface_.isLoopback()) continue;

        // if you don't expect the interface to be up you can skip this
        // though it would question the usability of the rest of the code
        if (!interface_.isUp()) continue;

        // iterate over the addresses associated with the interface
        Enumeration<InetAddress> addresses = interface_.getInetAddresses();
        for (InetAddress address : Collections.list(addresses)) {
          // look only for ipv4 addresses
          if (address instanceof Inet6Address) continue;

          // use a timeout big enough for your needs
          if (!address.isReachable(3000)) continue;

          return interface_;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * Returns if the host is currently reachable.
   *
   * <p>If the host is unreachable, this method will not try again for up to 30 seconds.
   *
   * @return If the host is reachable.
   */
  public boolean isAvailable() {
    if (!UpnpDiscoverer.getDevicePingDetection()) return true;

    // We are not protected from the remote address suddenly changing.
    InetAddress remoteAddress = this.remoteAddress;
    if (remoteAddress != null) {
      if (System.currentTimeMillis() > timeout) {
        try {
          boolean returnValue = remoteAddress.isReachable(UpnpDiscoverer.getDevicePingTimeout());

          if (returnValue) {
            return true;
          } else {
            logger.warn("Unable to ping the remote address {}.", remoteAddress.toString());
          }
        } catch (Exception e) {
          logger.error("Unable to ping the remote address {} => ", remoteAddress.toString(), e);
        }

        // Set the timeout for 30 seconds from now. This way when multiple capture devices
        // on one host are unavailable we don't waste time finding out what we already know
        // for at least 30 more seconds which should be more than enough time to find a
        // better capture device or come back to this one and try to use it anyway.
        timeout = System.currentTimeMillis() + 30000;
      }
      return false;
    }

    return true;
  }
 /**
  * Gets the next available address in this address pool.
  *
  * @return the next available address
  */
 public InetAddress getNextAvailableAddress() {
   if (freeList != null) {
     BigInteger next = freeList.getNextFree();
     if (next != null) {
       try {
         InetAddress ip = InetAddress.getByAddress(next.toByteArray());
         int pingCheckTimeout =
             DhcpServerPolicies.globalPolicyAsInt(Property.V4_PINGCHECK_TIMEOUT);
         if (pingCheckTimeout > 0) {
           try {
             if (ip.isReachable(pingCheckTimeout)) {
               log.warn("Next free address answered ping check: " + ip.getHostAddress());
               setUsed(ip);
               return getNextAvailableAddress(); // try again
             }
           } catch (IOException ex) {
             log.error("Failed to perform v4 ping check: " + ex);
           }
         }
         return ip;
       } catch (UnknownHostException ex) {
         log.error("Unable to build IPv4 address from next free: " + ex);
       }
     }
   }
   return null;
 }
Esempio n. 7
0
 private boolean canConnect() {
   try {
     URI host = new URI(this.endpoint);
     InetAddress addy = InetAddress.getByName(host.getHost());
     return addy.isReachable(2);
   } catch (Exception ex) {
     return false;
   }
 }
Esempio n. 8
0
 /**
  * ping测试
  *
  * @param ip
  * @param timeout
  * @return
  */
 public static boolean isReachable(String ip, int timeout) {
   try {
     InetAddress address = InetAddress.getByName(ip);
     return address.isReachable(timeout);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
Esempio n. 9
0
 public static boolean ping(String host, int timeout) {
   boolean result = false;
   pingErrorMessage = "No Error";
   try {
     InetAddress address = InetAddress.getByName(host);
     result = address.isReachable(timeout);
   } catch (Exception e) {
     result = false;
     pingErrorMessage = e.getMessage();
   } finally {
     return result;
   }
 }
 protected boolean pingable(InetAddress inetAddress) {
   try {
     return inetAddress.isReachable(20);
   } catch (IOException e) {
     log.debug(
         "Unable to contact server: "
             + inetAddress.getHostAddress()
             + " ("
             + e.getMessage()
             + ")");
     return false;
   }
 }
Esempio n. 11
0
  private boolean checkHost(String host) {
    try {
      InetAddress adress = InetAddress.getByName(host);

      boolean erreichbar = adress.isReachable(5000);
      return erreichbar;
    } catch (UnknownHostException e) {
      log.error(this.waageName + " ist mit der Adresse " + host + " unbekannt ", e);
      return (false);
    } catch (IOException e) {
      log.error(this.waageName + " ist mit der Adresse " + host + " nicht ereichbar ", e);
      return (false);
    }
  }
Esempio n. 12
0
 @Override
 protected Boolean doInBackground(NsdServiceInfo... nsi) {
   int count = nsi.length;
   if (count != 1) {
     Log.e(TAG, "found more then one NsdServiceInfo, dropping");
   }
   mNsdServiveInfo = nsi[0];
   InetAddress tmpIP = mNsdServiveInfo.getHost();
   boolean ret;
   try {
     ret = tmpIP.isReachable(10000);
     return ret;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   }
 }
  public boolean isReachable(String hostname) {
    boolean reachable = false;
    try {
      // also, this fails for an invalid address, like "www.sjdosgoogle.com1234sd"
      // InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
      InetAddress address = InetAddress.getByName(hostname);

      if (address.isReachable(10000)) {
        reachable = true;
      } else {
        reachable = false;
      }

    } catch (Exception ex) {
      System.out.println("DiscoveryClient : isReachable : Error " + ex.toString());
    }
    return reachable;
  }
Esempio n. 14
0
 private void Annoy_ping() {
   threadId = Thread.currentThread().getId();
   long startTime = System.currentTimeMillis();
   boolean toFinish = false;
   while (!toFinish) {
     try {
       InetAddress address = InetAddress.getByName(Adress);
       //               System.out.println("Name: " + address.getHostName());
       //              System.out.println("Addr: " + address.getHostAddress());
       System.out.println("Thread: " + threadId + " Reach: " + address.isReachable(500));
     } catch (UnknownHostException e) {
       System.err.println("Unable to lookup");
     } catch (IOException e) {
       System.err.println("Unable to reach");
     }
     toFinish = (System.currentTimeMillis() - startTime >= totalTime);
   }
 }
Esempio n. 15
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;
    }
  }
 public static InetAddress determineBindAddressBasedOnIsReachable(
     ArrayList<InetAddress> localIpAddresses, InetAddress destAddress) {
   for (InetAddress inetAddress : localIpAddresses) {
     try {
       if (inetAddress.isReachable(NetworkInterface.getByInetAddress(inetAddress), TTL, TIMEOUT)) {
         return inetAddress;
       }
     } catch (SocketException e) {
       RobotLog.v(
           String.format(
               "socket exception while trying to get network interface of %s",
               inetAddress.getHostAddress()));
     } catch (IOException e2) {
       RobotLog.v(
           String.format(
               "IO exception while trying to determine if %s is reachable via %s",
               destAddress.getHostAddress(), inetAddress.getHostAddress()));
     }
   }
   return Network.getLoopbackAddress();
 }
  private boolean systemPing(String hostname, int timeout) {
    boolean retval = false;

    InetAddress address = null;
    try {
      address = InetAddress.getByName(hostname);
      if (address == null) {
        logError(BaseMessages.getString(PKG, "JobPing.CanNotGetAddress", hostname));
        return retval;
      }

      if (log.isDetailed()) {
        logDetailed(BaseMessages.getString(PKG, "JobPing.HostName", address.getHostName()));
        logDetailed(BaseMessages.getString(PKG, "JobPing.HostAddress", address.getHostAddress()));
      }

      retval = address.isReachable(timeout);
    } catch (Exception e) {
      logError(BaseMessages.getString(PKG, "JobPing.ErrorSystemPing", hostname, e.getMessage()));
    }
    return retval;
  }
 public static InetAddress determineBindAddressBasedOnIsReachable(
     ArrayList<InetAddress> localIpAddresses, InetAddress destAddress) {
   Iterator it = localIpAddresses.iterator();
   while (it.hasNext()) {
     InetAddress inetAddress = (InetAddress) it.next();
     try {
       if (inetAddress.isReachable(NetworkInterface.getByInetAddress(inetAddress), TTL, TIMEOUT)) {
         return inetAddress;
       }
     } catch (SocketException e) {
       RobotLog.m254v(
           String.format(
               "socket exception while trying to get network interface of %s",
               new Object[] {inetAddress.getHostAddress()}));
     } catch (IOException e2) {
       RobotLog.m254v(
           String.format(
               "IO exception while trying to determine if %s is reachable via %s",
               new Object[] {destAddress.getHostAddress(), inetAddress.getHostAddress()}));
     }
   }
   return Network.getLoopbackAddress();
 }
  @Override
  public void run() {
    // TODO Auto-generated method stub
    super.run();

    int seconds = 60;
    if (SPConstants.getInstance().getSpProperty("refresh.time") != null) {
      try {
        seconds = Integer.parseInt(SPConstants.getInstance().getSpProperty("refresh.time"));
      } catch (NumberFormatException exception) {
        exception.printStackTrace();
        seconds = 60;
      }
    }

    long mili = seconds * 1000;

    StudentLoginDao loginDao = new StudentLoginDao();
    List<StudentLogin> studentLogins = loginDao.getAllStudentLogins();

    TimeIntervalDao timeIntervalDao = new TimeIntervalDao();
    timeIntervalDao.delAllTimeInterval();

    QPackDao qPackDao = new QPackDao();
    List<QPack> qPacks = qPackDao.getAllQPacks();
    if (qPacks != null)
      for (QPack qPack : qPacks) {
        qPack.setIntervalStatus("1");
        qPackDao.updateQPack(qPack);
      }

    mainLoop:
    while (true) {
      // Do your task
      System.out.println("Start...while");
      try {

        if (studentLogins != null) {

          for (StudentLogin studentLogin : studentLogins) {
            System.out.println("IP----->" + studentLogin.getIpAdd());

            TimeInterval timeInterval = new TimeInterval();
            timeInterval.setDate(new Date());
            timeInterval.setLogin(studentLogin);

            try {
              InetAddress address = InetAddress.getByName(studentLogin.getIpAdd());

              if (address.isReachable(10000)) {
                // active
                timeInterval.setActiveStatus("1");

              } else {
                // inactive
                timeInterval.setActiveStatus("0");
              }

            } catch (UnknownHostException e) {
              System.err.println("Unable to lookup web.mit.edu");
            } catch (IOException e) {
              System.err.println("Unable to reach web.mit.edu");
            }

            timeIntervalDao.addTimeInterval(timeInterval);
          }
        }

        qPacks = qPackDao.getAllQPacks();
        if (qPacks != null)
          for (QPack qPack : qPacks) {
            if (qPack.getIntervalStatus() != null && qPack.getIntervalStatus().equals("0")) {
              System.out.println("Breaking mainLoop.");
              break mainLoop;
            }
          }

        System.out.println("Waiting for " + seconds + " sec");
        Thread.sleep(mili);
      } catch (Exception e) {

      }
    }
  }
Esempio n. 20
0
  public static void main(String[] args) throws Exception {
    InetAddress as = InetAddress.getByName("www.infoq.com");

    System.out.println(as.isReachable(4000));
  }