I am in the process of writing a simple program that extracts computer names from MySQL Database then stores those names into a String array list (this part works fine). After that I wrote a class and a method that takes a String as a parameter (which will be the computer name) and tries to ping it. Here is the code for that class:
public class Ping
{
public void pingHost(String hostName)
{
try
{
InetAddress inet = InetAddress.getByName(hostName);
boolean status = inet.isReachable(5000);
if (status)
{
System.out.println(inet.getHostName() + " Host Reached\t" + inet.getHostAddress());
}
else
{
System.out.println(inet.getHostName() + " Host Unreachable");
}
}
catch (UnknownHostException e)
{
System.err.println(e.getMessage() + " Can't Reach Host");
}
catch (IOException e)
{
System.err.println(e.getMessage() + " Error in reaching the Host");
}
}
The problem is that I keep getting UnknownHostException
thrown for most computers even if I can ping them manually or if I hard code the computer name as the "hostName".
Here is what my main looks like:
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
ArrayList <String> list = new ArrayList<String>();
MySQLConnect myConnection = new MySQLConnect();
myConnection.importData(list);
Ping pingComputer = new Ping();
pingComputer.pingHost(list.get(87));
}
Right now I'm just trying to experiment with one computer which is throwing UnknownHostException
but can be pinged manually. Anyone have any idea why this is happening?
EDIT...
Just to explain this a little bit more. For example in main, if I pass these parameters to pingHost
:
pingComputer.pingHost("ROOM-1234");
It pings fine and returns correct host name/address. But list.get(87)
returns same host name "ROOM-1234" but throws UnknownHostException
? This has got me really confused and not sure why its not working.
EDIT
Wow finally figured it out. Reason ping was working when I was passing the string directly like so "ROOM-1234", was because there were no white spaces and getting is from array like so list.get(87)
returned same thing but when I checked charLength
, it returned a different value :) So I just ended up using trim
to get rid of white spaces and now itworks great.
pingComputer.pingHost(list.get(87).trim());
Thanks for all the suggestions!