Search code examples
javanetwork-programminginetaddress

How to create an INetAdress constructor


I have this code:

  import java.net.InetAddress;
  import java.net.UnknownHostException;

  public class NsLookup {

 private InetAddress inet = null;

 public void resolve(String host) {
   try {
     inet = InetAddress.getByName(host);

     System.out.println("Host name : " + inet.getHostName());
     System.out.println("IP Address: " + inet.getHostAddress());
  }
   catch (UnknownHostException e) { 
     e.printStackTrace(); 
   }
 }

 public static void main(String[] args) {
   NsLookup lookup = new NsLookup();
   lookup.resolve(args[0]);
 }
}

But I am trying to add a constructor to the class that initialises the InetAddress object, separating it from the resolve() method but unclear how to, any suggestions?


Solution

  • What you need is a simple constructor which accepts host name in the form of a String and initialises the InetAddress object for the same, which could be easily done as completed below :

      import java.net.InetAddress;
      import java.net.UnknownHostException;
    
      public class NsLookup {
    
        private InetAddress inet = null;
    
        // you need to define this extra constructor
        public NsLookup(String host){
        try{
           inet = InetAddress.getByName(host);
        }
        catch(UnknownHostException uhe){
          uhe.printStackTrace();
        }
        }
        // constructor ends here
    
        // Also you don't need to remove the argument received by the resolve() 
       // so that one could resolve other hostnames too.
    
        public void resolve(String host) {
         try {
            inet = InetAddress.getByName(host);
            System.out.println("Host name : " + inet.getHostName());
            System.out.println("IP Address: " + inet.getHostAddress());
         }
         catch (UnknownHostException e) { 
            e.printStackTrace(); 
         }
        }
    
     public static void main(String[] args) {
            NsLookup nsl = new NsLookup("YOUR-HOSTNAME");
            // add your rest code here
     }
    }