I am using this part of code to ping an ip address in java but only pinging localhost is successful and for the other hosts the program says the host is unreachable. I disabled my firewall but still having this problem
public static void main(String[] args) throws UnknownHostException, IOException { String ipAddress = "127.0.0.1"; InetAddress inet = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); ipAddress = "173.194.32.38"; inet = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); }
The output is:
Sending Ping Request to 127.0.0.1
Host is reachable
Sending Ping Request to 173.194.32.38
Host is NOT reachable
In Windows, hit Windows+R. In the Run window, type “cmd” into the search box, and then hit Enter. At the prompt, type “ping” along with the URL or IP address you want to ping, and then hit Enter.
Here's how it is done: Press the Windows key on your keyboard then start typing “command prompt” and select Command Prompt. Now, type “ping google.com” and hit Enter. To test the connection between your computer and your home router, enter the router's IP address.
InetAddress.isReachable()
according to javadoc:
".. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host..".
Option #1 (ICMP) usually requires administrative (root)
rights.
I think this code will help you:
public class PingExample { public static void main(String[] args){ try{ InetAddress address = InetAddress.getByName("192.168.1.103"); boolean reachable = address.isReachable(10000); System.out.println("Is host reachable? " + reachable); } catch (Exception e){ e.printStackTrace(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With