模拟Ping操作的一个Java类
本文为大家分享了模拟Ping操作的一个Java类,具体内容如下
importjava.io.IOException;
importjava.net.InetAddress;
importjava.net.UnknownHostException;
/**
*CreatedbyQiuJU
*on2014/9/21.
*/
publicclassSimplePingimplementsRunnable{
privatefinalObjectmEndLock=newObject();
privatebooleanIsEnd=false;
privateintarrivedCount=0;
privateintCount;
privateintTimeOut;
privateStringName;
privateintmEndCount;
privateStringmIp=null;
privatefloatmLossRate=1f;
privatefloatmDelay=0;
publicSimplePing(Stringname,intcount,inttimeOut){
Count=mEndCount=count;
TimeOut=timeOut;
Name=name;
for(inti=0;i<mEndCount;i++){
Threadthread=newThread(this);
thread.setDaemon(true);
thread.start();
}
if(!IsEnd){
try{
synchronized(mEndLock){
mEndLock.wait();
}
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
privatevoidsetEnd(booleanisArrived,longdelay,Stringip){
synchronized(mEndLock){
Count--;
if(isArrived){
arrivedCount++;
mDelay=(mDelay+delay)/2f;
if(ip!=null)
mIp=ip;
}
}
if(Count==0)
setEnd();
}
privatevoidsetEnd(){
mLossRate=(mEndCount-arrivedCount)/mEndCount;
IsEnd=true;
synchronized(mEndLock){
mEndLock.notifyAll();
}
}
@Override
publicvoidrun(){
longdelay=0;
booleanisArrived=false;
Stringip=null;
try{
longstartTime=System.currentTimeMillis();
InetAddressaddress=InetAddress.getByName(Name);
isArrived=address.isReachable(TimeOut);
delay=System.currentTimeMillis()-startTime;
ip=address.getHostAddress();
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
setEnd(isArrived,delay,ip);
}
}
publicStringgetIp(){
returnmIp;
}
publicfloatgetLossRate(){
returnmLossRate;
}
publicfloatgetDelay(){
returnmDelay;
}
publicbooleangetIsSucceed(){
returnarrivedCount>0;
}
}
在类中使用的是:
longstartTime=System.currentTimeMillis(); InetAddressaddress=InetAddress.getByName(Name); isArrived=address.isReachable(TimeOut); delay=System.currentTimeMillis()-startTime; ip=address.getHostAddress();
其中的:address.isReachable(TimeOut);方法,但是这个方法有一定局限性;当是Root模式下会发送ICMP进行Ping操作,这就比较真实了;但是如果是非Root模式下则是使用的Socket进行的模拟。
之所以说是中间类,也就是因为这个原因没有采用这个类。
以上就是本文的全部内容,希望对大家的学习有所帮助。