Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ping an IP address

Tags:

java

ping

host

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

like image 822
Mehdi Avatar asked Jul 16 '12 14:07

Mehdi


People also ask

How do I ping a network?

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.

Can you ping a public IP address?

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.


2 Answers

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.

like image 159
Arvik Avatar answered Oct 07 '22 01:10

Arvik


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();         }     } } 
like image 34
mohammad shojaeinia Avatar answered Oct 07 '22 01:10

mohammad shojaeinia