【发布时间】:2013-12-15 13:50:19
【问题描述】:
我开发了一个代码,用于使用套接字返回主机列表状态的多个主机和端口连接。问题是 ping 并返回仅 10 个连接的状态需要 5 分钟。任何想法为什么需要这么长时间?
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.PortUnreachableException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestIPList {
private static final Logger logger = LoggerFactory.getLogger(TestIPList.class);
static ArrayList<String> ipList = new ArrayList<String>();
public static ArrayList<String> captureValues() throws IOException,ConnectException
{
//Pattern ptn = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.
(\\d{1,3})\\.(\\d{1,3})");
Scanner ipFile = null;
String iList="";
ArrayList<String> ips = new ArrayList<String>();
ArrayList<String> returnList = new ArrayList<String>();
/*read the file at local path */
try {
ipFile = new Scanner (new File ("c:\\list.txt"));
}
catch(IOException e){
logger.debug( "[-] Cant open the file!");
System.exit(0);
}
/*Iterate thru the file */
while(ipFile.hasNext()){
ips.add(ipFile.next());
}
String[] ipPort;
for(int i=0;i<ips.size();i++){
iList = ips.get(i);
ipPort= iList.split(":");
Socket ss = null;
boolean status = false;
try {
/*Socket class.. here it is taking time to ping*/
ss = new Socket(ipPort[0], Integer.parseInt(ipPort[1]));
status = true; //there is a listening port
ss.close();
}
catch (IOException e) {
//e.printStackTrace();
}
finally {
if (ss != null) {
try {
ss.close();
}
catch(PortUnreachableException e)
{
ss=null;
System.err.println("Got an "+e);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
ss=null;
System.err.println("Got an "+e);
}
catch (IOException e) {
ss=null;
}
}
}
/*return status*/
if(status==true){
returnList.add("true");
}
else{
returnList.add("false");
}
}
/* return list of status*/
return returnList;
}
/*static method*/
public static void main(String a[]) throws IOException,ConnectException {
/* Into the main method */
ArrayList<String> ipexists = new ArrayList<String>();
ipexists =captureValues();
System.out.println("ArrayList Status---------"+captureValues());
/*End of the program*/
}
}
【问题讨论】: