Java Network Service Scanner

2019-04-15 02:15发布

问题:

I'm trying to write a class that will scan the local network for a service that will be running.

The problem is that if the address is not active (no reply) it hangs up on it for 5+ seconds which isn't good.

I want to have this scan done in a few seconds. Can anyone offer some advice?

My code part is below

        int port = 1338;
    PrintWriter out = null;
    BufferedReader in = null;

    for (int i = 1; i < 254; i++){

        try {
            System.out.println(iIPv4+i);
            Socket kkSocket = null;

            kkSocket = new Socket(iIPv4+i, port);

            kkSocket.setKeepAlive(false);
            kkSocket.setSoTimeout(5);
            kkSocket.setTcpNoDelay(false);  

            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            out.println("Scanning!");
            String fromServer;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Server here!"))
                    break;
            }

        } catch (UnknownHostException e) {

        } catch (IOException e) {

        }
    }

Thank you for the answers! Here's my code for anyone else looking for this!

        for (int i = 1; i < 254; i++){

        try {
            System.out.println(iIPv4+i);
            Socket mySocket = new Socket();
            SocketAddress address = new InetSocketAddress(iIPv4+i, port);

            mySocket.connect(address, 5);   

            out = new PrintWriter(mySocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            out.println("Scanning!");
            String fromServer;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Server here!"))
                    break;
            }

        } catch (UnknownHostException e) {

        } catch (IOException e) {

        }
    }

回答1:

You could try connecting to the server explicitly by invoking Socket.connect( address, timeout ).

 Socket kkSocket = new Socket();
 kkSocket.bind( null )/ // bind socket to random local address, but you might not need to do this
 kkSocket.connect( new InetSocketAddress(iIPv4+i, port), 500 ); //timeout is in milliseconds


回答2:

You can create an unconnected socket using the noarg constructor Socket() and then call connect(SocketAddress endpoint, int timeout) with a small timeout value.

Socket socket = new Socket();
InetSocketAddress endpoint = new InetSocketAddress("localhost", 80);
int timeout = 1;
socket.connect(endpoint, timeout);