|
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.DatagramPacket;
import java.io.IOException;
public class MyPing
{
static final int echoPort = 7;
static final int maxPingTime = 3000; // Milliseconds
static final int pingPollInterval = 100; // Milliseconds
public void ping(InetAddress dest)
{
String message = "test ping";
byte[] outmsg = message.getBytes();
int length = message.getBytes().length;
byte[] inmsg = new byte[length];
DatagramPacket outPacket = new DatagramPacket(outmsg, length);
DatagramPacket inPacket = new DatagramPacket(inmsg, length);
try
{
DatagramSocket socket = new DatagramSocket(echoPort, dest);
outPacket.setAddress(dest);
outPacket.setPort(echoPort);
socket.send(outPacket);
socket.setSoTimeout(5000);
socket.receive(inPacket);
System.out.println(new String(inmsg));
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.net.InetAddress;
import java.net.UnknownHostException;
class Tester
{
public static void main(String[] a)
{
try
{
InetAddress addr = InetAddress.getLocalHost();
new MyPing().ping(addr);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
}
} |
|