如何在“InetAddress”方法中传递“hostnames”数组,而不是传递一个主机名

时间:2013-02-14 10:07:10

标签: java hostname inetaddress

如何在下面的代码块中传递多个“主机名”,我们只传递一个主机名?有可能吗?

private static void run() {

  String host = "www.google.com";
  try {
    inetAddress = InetAddress.getAllByName(host);
    String all = "";
    for (int i = 0; i < inetAddress.length; i++) {
      all = all + String.valueOf(i) + " : " + inetAddress[i].toString() + "\n";
      Log.d("IPADDR", "IP Address : " + all);                  
      prefs.sethostIPaddress(context, all);  //Setting HostIP Address in Preference File
    }
  }
  catch (UnknownHostException e) {
       e.printStackTrace();
  }
} 

2 个答案:

答案 0 :(得分:1)

来自InetAddress没有采用Strings数组的方法。所以你不能这样做。

您可以创建自己的主机数组并使用for循环来获取InetAddress。像

String [] hosts = {"host1", "host2", "host3"};

for(String host : hosts){
   try {
      inetAddress = InetAddress.getAllByName(host);
      String all = "";
      for (int i = 0; i < inetAddress.length; i++) {
          all = all + String.valueOf(i) + " : " + inetAddress[i].toString() + "\n";
          Log.d("IPADDR", "IP Address : " + all);
          prefs.sethostIPaddress(context, all); //Setting HostIP Address in Preference File    
       }
    }
    catch (UnknownHostException e) {
          e.printStackTrace();
    }  
}

答案 1 :(得分:0)

我没有看到适当的API,为什么不只是传递一个Host数组并循环呢?

String[] hosts = {"www.google.com", "www.pippo.com", "...."};
for(String host : hosts){
  // Do your thing
}