Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Java to Ping server??

Status
Not open for further replies.

Mike2020

Programmer
Mar 18, 2002
55
US
Hi:

I want to ping server using the java, but I can't find which class/method to use. Could you please tell me how?

Thank you so much
 
Here is a way that you can ping a box on the web. The results of ping are a little os specific, but I think I took care of Windows and solaris at least. If you need to run the program on a different environment, you may need to account for that in your code.

import java.io.*;

public class Ping
{
public static boolean ping( String name )
{
boolean alive = false;
try
{
Process p = Runtime.getRuntime().exec( "ping " + name );
DataInputStream dis = new DataInputStream( new BufferedInputStream( p.getInputStream() ) );

// Solaris returns nothing if the machine is not
// found, but you need to check windows output
String s = null;
if( ( s = dis.readLine() ) != null )
{
// Check for false return for windows
if( !s.startsWith( "Unknown host" ) )
alive = true;
}
} catch( Exception e ){ e.printStackTrace( System.out ); }

return( alive );
}

public static void main( String args[] )
{
if( Ping.ping( args[0] ) )
System.out.println( args[0] + " is alive" );
else
System.out.println( args[0] + " is not alive" );
}
}

Hope that helps!

-gc
"I don't look busy because I did it right the first time."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top