Hello

I feel stupid for actually asking this but how do I ping a IP address in Java?

I have this code

try 
		{
			// Google.com
			if (InetAddress.getByAddress("173.194.35.133".getBytes()).isReachable(1000)==true)
			{
                                    //Boolean variable named network
				network=true; //Ping works
			}
			else
			{
				network=false; //Ping doesnt work
			}
		} 
		catch (UnknownHostException e3) 
		{
			System.out.println("ERROR: DNS server error " + e3.getLocalizedMessage());
		} 
		catch (IOException e3) 
		{
			System.out.println("ERROR: Some other error " + e3.getLocalizedMessage());
			
		}

The reason I use a IP address instead of a more common host name is because I have to also ping a internal 192.168.100.3 address which does not have a host name so Ill just do it more universal and just use IP addresses.....

Try this with variables defined and without the getbytes method for now:

try {             
     InetAddress adr = InetAddress.getByName("173.194.35.133");
     System.out.println("Reachable Host: "+adr.isReachable(3000));  
     boolean status = inet.isReachable(3000);  
     System.out.println("Reachable Host:" + status);      
}
catch (IOException e) {             
     e.printStackTrace();         
}

Either using the boolean or not.
Hope that helps :)

What is "inet.isReachable(3000);"???

This code

InetAddress adr=InetAddress.getByName("173.194.35.133"); //Google.com
			redexterna=adr.isReachable(3000);
			System.out.println("Value 1 " + redexterna);
			adr=InetAddress.getByName("192.168.2.3"); //A IP on my local network that does NOT exist
			redinterna=adr.isReachable(3000);
			System.out.println("Value 2 " + redinterna);
			Thread.sleep(5000);

Both give me false. Pinging to google works and pinging to that IP doesnt work in CMD....

Just to make sure :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.