Hotdot Cyber
Hotdot Cyber

Reputation: 393

Ping a device in Java

I am trying to ping a device using an IP address in Java but my code returns true even when the host is unreachable. I am using the InetAddress class. Here is my code:

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class JavaPinger //java class
{
    public static void main(String[] args)
    {
        System.out.println("Ping Poller Starts...");

        String ipAddress = "192.168.43.34"; //Ip Address

        try
        {
            if (!ipAddress.isEmpty())
            {
                InetAddress inet = InetAddress.getByName(ipAddress);// Can also use InetAddress.getByAddress but returns the same value
                System.out.println("Sending Ping Request to " + ipAddress);

                boolean status = inet.isReachable(5000); //Timeout = 5000 milli seconds

                if (status)
                {
                    System.out.println("Status : Host is reachable"+status);

                }
                else
                {
                    System.out.println("Status : Host is not reachable");
                }
            }
        }
        catch (IOException e)
        {
            System.err.println("Error in reaching the Host");
        }
    }
} 

Upvotes: 0

Views: 364

Answers (0)

Related Questions