欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

模拟Ping操作的一个Java类

程序员文章站 2024-03-31 19:51:10
本文为大家分享了模拟ping操作的一个java类,具体内容如下 import java.io.ioexception; import java.net.inet...

本文为大家分享了模拟ping操作的一个java类,具体内容如下

import java.io.ioexception;
import java.net.inetaddress;
import java.net.unknownhostexception;
 
/**
 * created by qiuju
 * on 2014/9/21.
 */
public class simpleping implements runnable {
 private final object mendlock = new object();
 private boolean isend = false;
 
 private int arrivedcount = 0;
 
 private int count;
 private int timeout;
 private string name;
 
 private int mendcount;
 private string mip = null;
 private float mlossrate = 1f;
 private float mdelay = 0;
 
 
 public simpleping(string name, int count, int timeout) {
  count = mendcount = count;
  timeout = timeout;
  name = name;
  for (int i = 0; i < mendcount; i++) {
   thread thread = new thread(this);
   thread.setdaemon(true);
   thread.start();
  }
  if (!isend) {
   try {
    synchronized (mendlock) {
     mendlock.wait();
    }
   } catch (interruptedexception e) {
    e.printstacktrace();
   }
  }
 }
 
 private void setend(boolean isarrived, long delay, string ip) {
  synchronized (mendlock) {
   count--;
   if (isarrived) {
    arrivedcount++;
    mdelay = (mdelay + delay) / 2f;
    if (ip != null)
     mip = ip;
   }
  }
  if (count == 0)
   setend();
 }
 
 private void setend() {
  mlossrate = (mendcount - arrivedcount) / mendcount;
 
  isend = true;
  synchronized (mendlock) {
   mendlock.notifyall();
  }
 }
 
 @override
 public void run() {
  long delay = 0;
  boolean isarrived = false;
  string ip = null;
  try {
   long starttime = system.currenttimemillis();
   inetaddress address = inetaddress.getbyname(name);
   isarrived = address.isreachable(timeout);
   delay = system.currenttimemillis() - starttime;
   ip = address.gethostaddress();
  } catch (unknownhostexception e) {
   e.printstacktrace();
  } catch (ioexception e) {
   e.printstacktrace();
  } catch (exception e) {
   e.printstacktrace();
  } finally {
   setend(isarrived, delay, ip);
  }
 }
 
 public string getip() {
  return mip;
 }
 
 public float getlossrate() {
  return mlossrate;
 }
 
 public float getdelay() {
  return mdelay;
 }
 
 public boolean getissucceed() {
  return arrivedcount > 0;
 }
}

在类中使用的是:

long starttime = system.currenttimemillis();
   inetaddress address = inetaddress.getbyname(name);
   isarrived = address.isreachable(timeout);
   delay = system.currenttimemillis() - starttime;
   ip = address.gethostaddress();

其中的:address.isreachable(timeout);方法,但是这个方法有一定局限性;当是root模式下会发送icmp进行ping操作,这就比较真实了;但是如果是非root模式下则是使用的socket进行的模拟。
之所以说是中间类,也就是因为这个原因没有采用这个类。

以上就是本文的全部内容,希望对大家的学习有所帮助。