Question:
If I can use the “InetAddress” class to acquire the IP address of a computer, is there a way to get the computer’s name from an IP address?
Answer:
“InetAddress” can be used both to discover the IP address of a host and to discover the host name corresponding to an IP address. When you call “InetAddress.getByName(String host),” the host argument can be either a host name or a text representation of an IP address.
For example, run the following program with www.sun.com as an argument and it will print:
Name: www.sun.comIP: 192.18.97.195
Run it with 192.18.97.195 as an argument and it will print the same thing (if www.sun.com maps to multiple IP addresses, the actual address that results when you run the program may differ).
import java.net.*;import java.io.*;public class lookup { public static void main(String[] args) { if(args.length != 1) { System.err.println("lookup host"); return; } try { InetAddress address; address = InetAddress.getByName(args[0]); System.out.println("Name: " + address.getHostName()); System.out.println("IP: " + address.getHostAddress()); } catch(IOException ioe) { ioe.printStackTrace(); } }}