如何创建一个INetAdress构造函数

时间:2015-10-29 15:26:20

标签: java network-programming inetaddress

我有这段代码:

  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]);
 }
}

但是我试图在初始化InetAddress对象的类中添加一个构造函数,将它与resolve()方法分开,但不清楚如何,任何建议?

1 个答案:

答案 0 :(得分:1)

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
 }
}