简体   繁体   中英

Java code for getting the status of multiple IP,Port using socket connection

I have developed a code which for multiple host and port connection using socket to return the status of the list of hosts. Problem is it is taking 5 mins to ping and return the status for only 10 connections. Any ideas why it takes so long?

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

}

You might want to try specifying a timeout:

SocketAddress sa = new InetSocketAddress(ipPort[0], Integer.parseInt(ipPort[1]));
Socket ss = new Socket();
int timeoutMillis = 500;
ss.connect(sa, timeoutMillis);

Edit: In order to do the same with multiple threads you could modify the code like this:

final ArrayList<String> ips = new ArrayList<String>();
// ..
final List<String> returnList = Collections.synchronizedList(new ArrayList<String>(ips));
Collections.fill(returnList, "false");

int nThreads = 10;
final ExecutorService es = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < ips.size(); i++) {
    final int index = i; // needs to be final to be available in local class
    es.execute(new Runnable() {
        @Override
        public void run() {
            String iList = ips.get(index);
            String[] ipPort = iList.split(":");
            final String host = ipPort[0];
            final int port = Integer.parseInt(ipPort[1]);
            Socket ss = null;
            boolean status = false;
            try {
                int timeoutMillis = 1500;
                InetAddress ia = InetAddress.getByName(host);
                // Edit: isReachable often fails for public sites
                //if (!ia.isReachable(timeoutMillis))
                //  throw new UnknownHostException(host);
                SocketAddress sa = new InetSocketAddress(ia, port);
                ss = new Socket();
                ss.connect(sa, timeoutMillis);
                status = true;
                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.set(index, "true");
            } else {
                returnList.set(index, "false");
            }
        }
    });
}
es.shutdown();
es.awaitTermination(60, TimeUnit.SECONDS);
List<Runnable> pending = es.shutdownNow();
if (!pending.isEmpty()) System.err.println("Pending threads: " + pending);

For an alternative multi-threaded, more complex example you may want to have a look at Ping.java of Oracles NIO and NIO.2 Examples .


Edit: Commented out the isReachable branch because it does rarely work with public websites.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM