Ping a computer

P

Percy

I have written a code for pinging in java ,which worke don some
computer but not in all.Can n e body figure out the problem.The code is
:


import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.geom.*;
import java.net.*;
import java.util.*;

public class Ping extends JPanel implements ActionListener
{
static DatagramSocket socket;
static final int DEFAULT_PORT = 7;
static final int UDP_HEADER = 20 + 8;
static final int BACKSPACE = 8;
static String host = null;
static int port, count = 32, delay = 1000, size = 64;
static boolean flood = false;
ImageIcon conn;
JButton b;
static Vector v;
JScrollPane sp;
JTextField tf;
static JList l;
String s,args;
JLabel l1,l2,li,l4;

public Ping()
{
setLayout(null);
// setBackground(new Color(20,67,137));
v=new Vector();
conn=new ImageIcon("emailme.gif");
li=new JLabel(conn);

l=new JList(v);
sp= new JScrollPane(l);
b=new JButton("ping");
tf= new JTextField();
l1=new JLabel("Enter IP ADDRESS");
l2=new JLabel("STATISTICS");
l4=new JLabel("PING A CLIENT");
setBackground(new Color(13,134,255));

l4.setFont(new Font("TIMES",Font.BOLD,30));

l4.setBounds(250,20,400,30);
b.setBounds(550,80,100,20);
tf.setBounds(280,80,200,20);
l1.setBounds(100,80,200,20);
l2.setBounds(300,120,200,20);
sp.setBounds(120,140,500,220);
li.setBounds(270,110,110,50);
l1.setFont(new Font("TIMES",Font.BOLD,15));
l1.setForeground(Color.black);
l2.setFont(new Font("TIMES",Font.BOLD,15));
l2.setForeground(Color.black);

add(l4);
add(b);
add(sp);
add(tf);
add(l1);
add(l2);
add(li);

b.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
args=tf.getText();
parseArgs(args);
try
{
init ();
}catch (IOException e1) {}

for (int i = 0; (i < count) || (count == 0); ++ i)
{
long past = System.currentTimeMillis ();
try
{
ping (i, past);
} catch (IOException e2){}

try
{
pong (i, past);
} catch (IOException e3){}
}
socket.close ();
printStats ();
}
}

static void parseArgs (String args)
{
if (host != null)
syntaxError ();
int colon = args.indexOf (":");
host = (colon > -1) ? args.substring (0, colon) : args;
port = ((colon > -1) && (colon < args.length () - 1)) ?
Integer.parseInt (args.substring (colon + 1)) :
DEFAULT_PORT;

if (host == null)
syntaxError ();
}

static void syntaxError()
{
throw new IllegalArgumentException
("Ping [-c count] [-i wait] [-s packetsize] [-f]
<hostname>[:<port>]");
}


static byte[] outBuffer, inBuffer;
static DatagramPacket outPacket, inPacket;

static void init () throws IOException
{
socket = new DatagramSocket ();
outBuffer = new byte[Math.max (12, size - UDP_HEADER)];
outPacket = new DatagramPacket (outBuffer,
outBuffer.length,InetAddress.getByName (host), port);
inBuffer = new byte[outBuffer.length];
inPacket = new DatagramPacket (inBuffer, inBuffer.length);
}

static int sent = 0;

static void ping (int seq, long past) throws IOException
{
writeInt (seq, outBuffer, 0);
writeLong (past, outBuffer, 4);
socket.send (outPacket);
++ sent;
if (flood)
{
System.out.write ('.');
System.out.flush ();
}
}

static final void writeInt (int datum, byte[] dst, int offset)
{
dst[offset] = (byte) (datum >> 24);
dst[offset + 1] = (byte) (datum >> 16);
dst[offset + 2] = (byte) (datum >> 8);
dst[offset + 3] = (byte) datum;
}

static final void writeLong (long datum, byte[] dst, int offset)
{
writeInt ((int) (datum >> 32), dst, offset);
writeInt ((int) datum, dst, offset + 4);
}

static int received = 0;

static void pong (int seq, long past) throws IOException
{
long present = System.currentTimeMillis ();
int tmpRTT = (maxRTT == 0) ? 500 : (int) maxRTT * 2;
int wait = Math.max (delay, (seq == count - 1) ? tmpRTT : 0);
do
{
socket.setSoTimeout (Math.max (1, wait - (int) (present -
past)));
socket.receive (inPacket);
++ received;
present = System.currentTimeMillis ();
processPong (present);
} while ((present - past < wait) && !flood);
}

static long minRTT = 100000, maxRTT = 0, totRTT = 0;

static void processPong (long present)
{
int seq = readInt (inBuffer, 0);
long when = readLong (inBuffer, 4);
long rtt = present - when;
if (!flood)
{
v.add((inPacket.getLength () + UDP_HEADER) +" bytes from " +
inPacket.getAddress ().getHostName () +": seq no " + seq + " time=" +
rtt + " ms");
l.setListData(v);
}
else
{
System.out.write (BACKSPACE);
System.out.flush ();
}
if (rtt < minRTT) minRTT = rtt;
if (rtt > maxRTT) maxRTT = rtt;
totRTT += rtt;
}

static final int readInt (byte[] src, int offset)
{
return (src[offset] << 24) | ((src[offset + 1] & 0xff) << 16)
|((src[offset + 2] & 0xff) << 8) | (src[offset + 3] & 0xff);
}

static final long readLong (byte[] src, int offset)
{
return ((long) readInt (src, offset) << 32) |((long) readInt
(src, offset + 4) & 0xffffffffL);
}

static void printStats ()
{
v.add(sent + " packets transmitted, " + received + " packets
received, " +(100 * (sent - received) / sent) + "% packet loss");
l.setListData(v);
if (received > 0)
{
v.add("round-trip min/avg/max = " + minRTT + '/' + ((float)
totRTT / received) + '/' + maxRTT + " ms");
l.setListData(v);
}
}
}

Please contact me personally at my email id:p[email protected]
 
T

Thomas Fritsch

Percy said:
I have written a code for pinging in java ,which worke don some
computer but not in all.
What exactly do you mean with "doesn't work"?
Do you get an exception after some time? After what time?
Or do you get no output at all, and your program seems to hang?
Can n e body figure out the problem.The code is
: [...]

Please contact me personally at my email id:p[email protected]
Sorry, that is not the way news-groups work.
If it is too much trouble for you to check for answers given here, then
why should anyone take the trouble to solve your problem for free and
answer you by email?
If you really want personal support, then you can choose a commercial
help-desk and pay them $ for their work.
 
E

EJP

This looks like you are trying to implement the PING protocol over UDP,
and at the same time implement the UDP protocol over UDP, so you are
trying to build PING/UDP/UDP.

There are two mistakes here:

(1) UDP is already implemented: you don't need all that header offset stuff

(2) PING is not a UDP protocol, it is an ICMP protocol, and you can't do
it from Java without JNI code.
 
I

IchBin

:: I have written a code for pinging in java ,which worke don some
:: computer but not in all.Can n e body figure out the problem.The code is
:::

[snip code]

You can use this one or compare your code to this. The default port is 80.

The run format is: java Ping [port] host..

/*
* @(#)Ping.java 1.2 01/12/13 Connect to each of a list of hosts and measure
the
* time required to complete the connection. This example uses a selector
and
* two additional threads in order to demonstrate non-blocking connects and
the
* multithreaded use of a selector.
*
* Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
met:
*
* -Redistributions of source code must retain the above copyright notice,
this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF
OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE
THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*/

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.regex.Pattern;

public class Ping
{

// The default daytime port
static int DAYTIME_PORT = 80;
// The port we'll actually use
static int port = DAYTIME_PORT;

// Representation of a ping target
//
static class Target
{

InetSocketAddress address;
SocketChannel channel;
Exception failure;
long connectStart;
long connectFinish = 0;
boolean shown = false;

Target(String host)
{
try
{
address = new InetSocketAddress(InetAddress.getByName(host),
port);
} catch (IOException x)
{
failure = x;
}
}

void show()
{
String result;
if (connectFinish != 0)
result = Long.toString(connectFinish - connectStart) + "ms";
else if (failure != null)
result = failure.toString();
else
result = "Timed out";
System.out.println(address + " : " + result);
shown = true;
}

}

// Thread for printing targets as they're heard from
//
static class Printer extends Thread
{
LinkedList pending = new LinkedList();

Printer()
{
setName("Printer");
setDaemon(true);
}

void add(Target t)
{
synchronized (pending)
{
pending.add(t);
pending.notify();
}
}

/**
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
public void run()
{
try
{
for (;;)
{
Target t = null;
synchronized (pending)
{
while (pending.size() == 0)
pending.wait();
t = (Target)pending.removeFirst();
}
t.show();
}
} catch (InterruptedException x)
{
return;
}
}

}

// Thread for connecting to all targets in parallel via a single
selector
//
static class Connector extends Thread
{
Selector sel;
Printer printer;

// List of pending targets. We use this list because if we try to
// register a channel with the selector while the connector thread
is
// blocked in the selector then we will block.
//
LinkedList pending = new LinkedList();

Connector(Printer pr) throws IOException
{
printer = pr;
sel = Selector.open();
setName("Connector");
}

// Initiate a connection sequence to the given target and add the
// target to the pending-target list
//
void add(Target t)
{
SocketChannel sc = null;
try
{

// Open the channel, set it to non-blocking, initiate
connect
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(t.address);

// Record the time we started
t.channel = sc;
t.connectStart = System.currentTimeMillis();

// Add the new channel to the pending list
synchronized (pending)
{
pending.add(t);
}

// Nudge the selector so that it will process the pending
list
sel.wakeup();

} catch (IOException x)
{
if (sc != null)
{
try
{
sc.close();
} catch (IOException xx)
{}
}
t.failure = x;
printer.add(t);
}
}

// Process any targets in the pending list
//
void processPendingTargets() throws IOException
{
synchronized (pending)
{
while (pending.size() > 0)
{
Target t = (Target)pending.removeFirst();
try
{

// Register the channel with the selector,
indicating
// interest in connection completion and attaching
the
// target object so that we can get the target back
// after the key is added to the selector's
// selected-key set
t.channel.register(sel, SelectionKey.OP_CONNECT, t);

} catch (IOException x)
{

// Something went wrong, so close the channel and
// record the failure
t.channel.close();
t.failure = x;
printer.add(t);

}

}
}
}

// Process keys that have become selected
//
void processSelectedKeys() throws IOException
{
for (Iterator i = sel.selectedKeys().iterator(); i.hasNext();)
{

// Retrieve the next key and remove it from the set
SelectionKey sk = (SelectionKey)i.next();
i.remove();

// Retrieve the target and the channel
Target t = (Target)sk.attachment();
SocketChannel sc = (SocketChannel)sk.channel();

// Attempt to complete the connection sequence
try
{
if (sc.finishConnect())
{
sk.cancel();
t.connectFinish = System.currentTimeMillis();
sc.close();
printer.add(t);
}
} catch (IOException x)
{
sc.close();
t.failure = x;
printer.add(t);
}
}
}

volatile boolean shutdown = false;

// Invoked by the main thread when it's time to shut down
//
void shutdown()
{
shutdown = true;
sel.wakeup();
}

// Connector loop
//
/**
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
public void run()
{
for (;;)
{
try
{
int n = sel.select();
if (n > 0)
processSelectedKeys();
processPendingTargets();
if (shutdown)
{
sel.close();
return;
}
} catch (IOException x)
{
x.printStackTrace();
}
}
}

}

/**
* @param args
* @throws InterruptedException
* @throws IOException
*/
public static void main(String[] args) throws InterruptedException,
IOException
{
if (args.length < 1)
{
System.err.println("Usage: java Ping [port] host...");
return;
}
int firstArg = 0;

// If the first argument is a string of digits then we take that
// to be the port number to use
if (Pattern.matches("[0-9]+", args[0]))
{
port = Integer.parseInt(args[0]);
firstArg = 1;
}

// Create the threads and start them up
Printer printer = new Printer();
printer.start();
Connector connector = new Connector(printer);
connector.start();

// Create the targets and add them to the connector
LinkedList targets = new LinkedList();
for (int i = firstArg; i < args.length; i++)
{
Target t = new Target(args);
targets.add(t);
connector.add(t);
}

// Wait for everything to finish
Thread.sleep(2000);
connector.shutdown();
connector.join();

// Print status of targets that have not yet been shown
for (Iterator i = targets.iterator(); i.hasNext();)
{
Target t = (Target)i.next();
if (!t.shown)
t.show();
}

}

}


Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor, Regular Guy (1952-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,913
Messages
2,570,027
Members
46,421
Latest member
WaylonBran

Latest Threads

Top