Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Oct 24, 2000

Reverse DNS

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.com
IP: 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();
    }
  }
}

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap