Monday, December 15, 2008

HostLookup

import java.net.*;
import java.io.*;
public class HostLookup {
public static void main(String[] args) {
if (args.length > 0) {

for (int i = 0; i < args.length; i++) {
System.out.println(lookup(args[i]));
}
}
else {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println(
"Enter names and IP addresses.Enter \"exit\" or \"quit\" to quit.");
try {
while (true) {
String host = in.readLine();
if (host.equalsIgnoreCase("exit") ||
host.equalsIgnoreCase("quit")) {
break;
}
System.out.println(lookup(host));
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
private static String lookup(String host) {
InetAddress node;
try {
node = InetAddress.getByName(host);
}
catch (UnknownHostException ex) {
return "Cannot find host " + host;
}
if (isHostname(host)) {
//Domain Name
return node.getHostAddress();
}
else {
// IP
return node.getHostName();
}
}
//Check host is domain name or IP
private static boolean isHostname(String host) {
char[] ca = host.toCharArray();
for (int i = 0; i < ca.length; i++) {
if (!Character.isDigit(ca[i])) {
if (ca[i] != '.')return true;
}
}
return false;
}
}