【问题标题】:How to create an INetAdress constructor如何创建 INetAddress 构造函数
【发布时间】:2015-10-29 15:26:20
【问题描述】:

我有这个代码:

  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() 方法分开,但不清楚如何做,有什么建议吗?

【问题讨论】:

  • 请不要给标签发垃圾邮件,这个问题与Python无关。

标签: java network-programming inetaddress


【解决方案1】:

您需要的是一个简单的构造函数,它以字符串的形式接受主机名并为其初始化 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
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多