【问题标题】:Java Network Service ScannerJava 网络服务扫描器
【发布时间】:2011-02-10 14:55:19
【问题描述】:

我正在尝试编写一个类来扫描本地网络以查找将要运行的服务。

问题是,如果地址不活跃(没有回复),它会挂断 5 秒以上,这是不好的。

我想在几秒钟内完成此扫描。谁能给点建议?

我的代码部分如下

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

        }
    }

感谢您的回答!这是我的代码,供其他人寻找!

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

        }
    }

【问题讨论】:

    标签: java sockets networking network-scan


    【解决方案1】:

    您可以尝试通过调用 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】:

    您可以使用 noarg 构造函数 Socket() 创建一个未连接的套接字,然后使用一个小的超时值调用 connect(SocketAddress endpoint, int timeout)

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

    【讨论】:

    • 超时时间以毫秒为单位,所以一秒的超时时间应该等于 1000。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2011-09-18
    • 2011-02-28
    • 2015-05-01
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多