Java Network Service Scanner

社会主义新天地 提交于 2019-12-06 15:06:04

问题


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);


来源:https://stackoverflow.com/questions/4958613/java-network-service-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!