0

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");
        }
    }
} 
user207421
  • 305,947
  • 44
  • 307
  • 483
Hotdot Cyber
  • 361
  • 1
  • 5
  • 21
  • 1
    How do you know the host is unreachable? – user207421 Dec 04 '19 at 03:51
  • The code seems fine and also works correctly on my machine. Make sure that you know if you can ping the address from command prompt. – Abdul Alim Shakir Dec 04 '19 at 03:57
  • form cmd I get this: Ping 192.168.43.34 Reply from 192.168.43.213:Destination host unreachable but my code status is true and returns reachable. – Hotdot Cyber Dec 04 '19 at 04:07
  • Can you telnet to 192.168.43.34? Or get a 'connection refused' when doing so? `isReachable()` doesn't use ICMP, it uses TCP, so the results aren't necessarily the same as for `ping`. And why is 192.168.43.213 a route for 192.168.43.34? – user207421 Dec 04 '19 at 04:09
  • Your code doesn't return anything. Your argument is invalid. – LowKeyEnergy Dec 04 '19 at 13:38

0 Answers0