Java Program to Ping an IP address

In this tutorial, we are gonna learn how to ping an IP address using Java program.

This program will help you to check the reachability of the host or website on an IP network. It will measure the amount of time taken by the message from the origin to the destination computer and back to the origin computer.

Internet Control Message Protocol (ICMP):

Internet Control Message Protocol (ICMP) is used by pin by echoing request packets to the target host and waiting for an ICMP echo reply.

This program helps in reporting errors, packet loss and statistical summary of the results. ICMP is used by routers to send and receive error messages informing whether a request to service is available or not.

How to ping an IP address in Java

// Java Program to Ping an IP address 
import java.io.*; 
import java.net.*; 
import java.util.Scanner;
class Main

 
{ 
  
// Sends ping request to a provided IP address 
  public static void sendPingRequest(String ipAddress) 
              throws UnknownHostException, IOException 
  { 
    InetAddress geek = InetAddress.getByName(ipAddress); 
    System.out.println("Sending Ping Request to " + ipAddress); 
    if (geek.isReachable(5000)) 
      System.out.println("Host is reachable"); 
    else
      System.out.println("Sorry ! We can't reach to this host"); 
  } 
  
  // Driver code 
  public static void main(String[] args) 
          throws UnknownHostException, IOException 
{ 
  
  String ipAddress;
  Scanner sc=new Scanner(System.in);
  System.out.println("Enter ipAddress");
  ipAddress=sc.next();
  sendPingRequest(ipAddress);

} 
}
  • Here we will enter the IP address.
  • Then it will send ping request to the provided IP address.
  • If the host is reachable the output will be “host is reachable”
  • Otherwise, it will be “sorry¬† ! we can’t reach to this host”

 

Output: If the host is reachable.

Enter ipAddress
127.0.0.1
Sending Ping Request to 127.0.0.1
Host is reachable

Output: If the host is not reachable.

Enter ipAddress
192.168.0.1
Sending Ping Request to 192.168.0.1
Sorry ! We can't reach to this host

You may also read:

Leave a Reply

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