Home > Tutorial > Java Ping Sample Code

Java Ping Sample Code

I was sitting around and thought it would be fun to write a Java program that will ping a device ip address or an internet URL. Sounds fun right? The concept is pretty simple. If you open up your CMD window in Windows, you can ping your localhost, which is 127.0.0.1 like you see below. So let’s do the same thing in Java.


Java Ping Step One

Since one of the key features of Java is that it can run on multiple platforms (windows, linux, etc), we need to determine our environment because the ping command will use either “-n” or “-c”. This ping parameter sets the number of packets to send. We just want to send 1 for efficiency. We set the ping command String based on the platform.

//If running on Windows platform use "-n" option
if(System.getProperty("os.name").startsWith("Windows")) 
{
   pingCommand = "ping -n 1 " + hostname;
} 
//Else other platform, use "-c" option
else 
{
   pingCommand = "ping -c 1 " + hostname;
}


Java Ping Step Two

In order to execute the ping command, we need to interface with the running environment, which can be done using the Runtime class. Calling Runtime.getRunTime() will return the Runtime object of the current Java application. From there we call the exec() method and feed it our ping command line string. The exec() method will return a Process object.

Process myProcess = Runtime.getRuntime().exec(pingCommand);


Java Ping Step Three

The next step is to call waitFor() method of Process class to give the exec time to return after running our ping command. This is a blocking call that will drop through once something is returned. The last part is to evaluate the ping process. If no exit value was returned, the ping was successful. Otherwise, the ping command failed.

myProcess.waitFor();
         
if(myProcess.exitValue() == 0) 
{ 
	result = true; 
}
else 
{ 
	result = false; 
}


Java Ping Step Four

The last step is to do some cleanup. It’s a good coding practice to call the destroy() method of the Process object. I am sure the garbage collector would take care of it, but I still like to do the cleanup.

myProcess.destroy();


Java Ping Full Sample Code

The Java program is simple and does work after compiling and running. I have set hostname variable to the localhost of my windows laptop. You should be able to ping any ip address or URL you have connectivity to.

package com.jcd.java.tutorials;

public class JavaPinger 
{

	public static void main(String[] args) 
	{
		
		//Define an ipaddress to ping or even a URL address
		String hostname = "127.0.0.1";
		
		//Create new Pinger instance
		Pinger pinger = new Pinger(hostname);
		
		//Call command line ping and get response
		boolean response = pinger.commandLinePing();
		
		if(response)
		{
			System.out.println("Successfull Ping of "+hostname);
		}
		else
		{
			System.out.println("Unsuccessfull Ping of "+hostname);
		}

	}

}

//Pinger class will handle pinging a host
class Pinger
{
	String pingCommand;
	
	
	//Constructor
	public Pinger(String hostname)
	{
		//If running on Windows platform use "-n" option
		if(System.getProperty("os.name").startsWith("Windows")) 
		{
            pingCommand = "ping -n 1 " + hostname;
        } 
		//Else other platform, use "-c" option
		else 
        {
            pingCommand = "ping -c 1 " + hostname;
        }
	}
	
	public boolean commandLinePing() 
	{
		boolean result = false;
		
		try
		{	
			//Call Runtime Exec and give it command to run
			Process myProcess = Runtime.getRuntime().exec(pingCommand);
        
			//Wait for a response or return
			myProcess.waitFor();
         
        
			if(myProcess.exitValue() == 0) 
			{ 
				result = true; 
			}
			else 
			{ 
				result = false; 
			}
        
			//Cleanup this Runtime process
			myProcess.destroy();
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
		
        //Return the result
		return result;
	}
	
}


Java Ping Sample Output

Since I set the ip address to ping as my localhost, it will always be successful.

Successfull Ping of 127.0.0.1


Conclusion

This was a fun exercise on writing a simple ping program using Java. It’s a good working basic sample that has endless possibilities for enhancements. We could have the ping program read in a file that contains a list of ip addresses that need to be pinged. While I did not mention it, there is another way to simulate a ping using a Java class.



References:

Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

(1) Comment

  1. Gary

    This is a pretty good ping example. I recall seeing another way to ping a host that doesn’t involve using Runtime but can’t remember what it was.

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot