I am trying to find out the information of all connected client in my network. I am able to find out the client(is reachable) but can't fetch information about him. I need only the host name(computer name), but following code only print the IP address. What i am missing?
private void getListOfHost(){
String subnet="192.168.0";
int timeout=100;
for (int i=2;i<15;i++){
String host=subnet + "." + i;
try {
if (InetAddress.getByName(host).isReachable(timeout)) {
InetAddress address = InetAddress.getByName(host);
System.out.println(host + " is reachable");
System.out.println("Canonical host: " + address.getCanonicalHostName());
System.out.print("Host name: " + address.getHostName() + "\n");
}
}
catch(Exception e){e.printStackTrace();}
}
}
192.168.0.6 is reachable
Canonical host: 192.168.0.6
Host name: 192.168.0.6
You're not missing anything in the code,but,the source of error is the security manager/firewall of the called system.
The Oracle docs for the InetAddress.getCanonicalHostname() states that :-
Returns:
the fully qualified domain name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.
The Oracle docs for the InetAddress.getHostname() states that :-
Returns:
the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.
Solution :-
Whatever system you want to enquire host-name of,just disable the firewall of that system. The security managers will always block system-specific enquiries about the other systems in the network as it is considered not an information to be shared(unsecure). You should always keep this thing in mind.