This article has shared a Java class that simulates ping, as follows
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; }
}
Used in the class are:
Long starttime = System.currenttimemillis ();
InetAddress address = Inetaddress.getbyname (Name);
isarrived = address.isreachable (TimeOut);
Delay = System.currenttimemillis ()-StartTime;
ip = address.gethostaddress ();
Of these: Address.isreachable (TimeOut); method, but this method has some limitations; when it is in root mode, it sends ICMP to ping, which is more real. , but if it is in non-root mode, it is a simulation of the socket being used.
It is said that the middle class, which is because of this reason did not adopt this class.
The above is the entire content of this article, I hope to help you learn.