import jicmp.*; import java.io.IOException; import java.net.UnknownHostException; import java.util.Random; class Ping extends Thread { static int number = 0; static String host = ""; public static void main(String args[]) { host = args[0]; Ping t1 = new Ping(); t1.setPriority(Thread.MIN_PRIORITY); t1.start(); } public synchronized void run() { ++number; int how_many_packets_to_send = 5; short contor; short seq_no = 0; jICMP socket = null; Thread t; // create a raw socket to localhost, with 10000ms timeout. socket = new jICMP(host); socket.setTimeout(3); try { for(contor = 0;contor < how_many_packets_to_send; contor++ ) { // create an ICMP packet with type ECHO_REQUEST, code 0, ID 12,and // secquence number starting from 0. Do not run this program while another // one is running. The packets sent by one will be received by the other // because the both have the same ID. ICMPPacket sendpak = new ICMPPacket(ICMPPacket.ICMP_ECHOREQ, (byte)0, (short)number, (short)(seq_no++ % 127)); // The packet can also carry data. The maximum length is 996 bytes. // The data could be anything ( usualy is the time when the packet // was sended so we can compute the roundtrip.). Use the // pak.setBuffer(buffer) to set the data. For now, we don't send // anything. // send it! try { System.out.println("Pinging " + socket.getHostName() + " with " + sendpak.getSize() + " bytes."); socket.send(sendpak); } catch(TimeOutException toe) { System.out.println(toe.getMessage()); continue; } catch(UnknownHostException uhe) { System.out.println("Unknoen Host: " + uhe.getMessage()); System.exit(0); } catch(IOException ioe) { System.out.println("An IO Exception has occured."); System.out.println(ioe.getMessage()); System.exit(0); } // make place for the answer! ICMPPacket recvpak = null; // start listening for the answer. for(;;) { try { recvpak = null; recvpak = socket.read(); // if nothing happens, then it could be a timeout error, so keep trying. if (recvpak == null) continue; // if it is an answer if(recvpak.getType() == ICMPPacket.ICMP_ECHOREPLY) // if it is OUR answer if ( recvpak.getID() == number ) { System.out.println("Replied. The packet no :" + recvpak.getSequenceNumber()); break; } } catch(TimeOutException toe) { System.out.println("timed out."); } catch(UnknownHostException uhe) { System.out.println("Unknown Host: " + uhe.getMessage()); System.exit(0); } catch(IOException ioe) { System.out.println("An IO Exception has occured."); System.out.println(ioe.getMessage()); System.exit(0); } } try { t = Thread.currentThread(); t.sleep(1000); } catch(InterruptedException ie) { System.out.println("Intrerupt"); } } } finally { socket.destroy(); } } }