Thursday, 18 September 2014

Code for finding the Hostname for IP's using Java

I was working for something, where i need Hostname for thousands of IP's.

So i though to write a simple program in java, below is the source code, the program will take the IP list as i/p and will give you the hostname as o/p.



import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

public class hostname {

    public static void main(String gk[]){
    
        File file = new File("C:\\GIVE YOUR FILE PATH\\ip.txt");
               try {

            Scanner scanner = new Scanner(file);
            BufferedWriter writer = null;
           
           
            File f =new File ("C:\\OUTPUT EXCEL FILE PATH\\ip.xls");
            f.createNewFile();
           
            writer = new BufferedWriter(new FileWriter(f));


            while (scanner.hasNextLine())
            {
                String line = scanner.nextLine();
                //System.out.println(line);
               
                InetAddress host = InetAddress.getByName(line);
                //System.out.println(host.getHostName());
               writer.write(line+"\t"+host.getHostName());
                writer.newLine();
               
               
            }
            writer.flush();
            writer.close();
            scanner.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment