如何创建 INetAddress 构造函数

How to create an INetAdress constructor

我有这个代码:

  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 对象的 class 添加构造函数,将其与 resolve() 方法分开,但不清楚如何操作,有什么建议吗?

您需要的是一个简单的构造函数,它接受字符串形式的主机名并为此初始化 InetAddress 对象,这很容易完成,如下所示:

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