本文为大家分享了模拟ping操作的一个java类、具体内容如下
java.io.ioexception; import java.net.inetAddress; import java.net.unknownhostexception; /** * 2014/9/21にQiuju *によって作成されました。 */public class simpleping runnable {private final object mendlock = new object();プライベートブールISEND = false; private int contercountcount = 0;プライベートインクカウント;プライベートINTタイムアウト;プライベート文字列名; Private int mendcount;プライベート文字列mip = null;プライベートフロートmlossrate = 1f;プライベートフロートmdelay = 0; public simpleping(string name、int count、int timeout){count = mendcount = count;タイムアウト=タイムアウト; name = name; for(int i = 0; i <mendcount; i ++){thread thread = newスレッド(this); thread.setDaemon(true); thread.start(); } if(!isend){try {synchronized(mendlock){mendlock.wait(); }} catch(arturnedexception e){e.printstacktrace(); }}} private void setend(boolean isarrived、long delay、string ip){synchronized(mendlock){count--; if(isarrived){conterincount ++; mdelay =(mdelay + delay) / 2f; if(ip!= null)mip = ip; }} if(count == 0)setEnd(); } private void setend(){mlossrate =(mendcount -conterincount) / mendcount; ISEND = true;同期(mendlock){mendlock.notifyall(); }} @Override public void run(){long delay = 0; boolean isarrived = false;文字列IP = null; try {long starttime = system.currenttimemillis(); inetAddressアドレス= 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(); }最後に{setend(isarrived、delay、ip); }} public string getIp(){return mip; } public float getLossrate(){return mlossrate; } public float getDelay(){return mdelay; } public boolean getissuc comed(){return contearconcount> 0; }}在类中使用的是:
long starttime = system.currenttimemillis(); inetAddressアドレス= inetAddress.getByname(name); iSarrived = address.isreachable(Timeout); delay = system.currenttimemillis() - starttime; ip = address.gethostaddress();
其中的:address.isreachable(タイムアウト);方法、但是这个方法有一定局限性;当是root模式下会发送ICMP进行ping操作、这就比较真实了;但是如果是非ルートソケット进行的模拟。
之所以说是中间类、也就是因为这个原因没有采用这个类。
以上就是本文的全部内容、希望对大家的学习有所帮助。