Home ProgrammingJava Java: host2IP – find the IP address from a host name

Java: host2IP – find the IP address from a host name

by Kliment Andreev
4.5K views

Recently, I have to find IP addresses for a bunch of hosts from a text file. This JAVA program uses Windows nslookup command to find the IP from a host. The input parameter is a text file with the names of the hosts, each host in a separate line.

e.g.
hostname1
hostname2

The output is on the screen in the form of:
hostname1IP address1
hostname2IP address2

You can redirect this output to a file “>” and import it in a spreadsheet program.

package host2ip;
import java.io.*;
  
public class Main {
  
     public static void main(String[] args) {
  
         String strIP = null;
         String strInput = null;
        
         try{
             FileInputStream fstream = new FileInputStream(args[0]);
             DataInputStream in = new DataInputStream(fstream);
             BufferedReader br = new BufferedReader(new InputStreamReader(in));
             String strLine;
             while ((strLine = br.readLine()) != null){
                 try {
                     Process p = Runtime.getRuntime().exec("nslookup " + strLine);
                     BufferedReader stdInput = new BufferedReader(new
                     InputStreamReader(p.getInputStream()));
                     while ((strInput = stdInput.readLine()) != null) {
                         if (strInput.contains("Address: ")){
                             strIP = strInput.substring(10);
                         }
                     }
                     System.out.println(strLine + " " + strIP);
                 }
                 catch (IOException e) {
                     System.out.println("Exception: ");
                     e.printStackTrace();
                     System.exit(-1);
                 }
             }
             in.close();
             } catch (Exception e){
                 System.err.println("Error: " + e.getMessage());
             }
     }
 }

Related Articles

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More