在java / jsp中telneting ip / port

时间:2012-09-19 19:50:51

标签: java html jsp

我正在尝试创建一个telnet ip port的脚本,以查看服务器是启动还是关闭。 (就像你在windows命令提示符中所做的那样.cmd [enter] => telnet 11.111.11.11 200(ip& port)如果连接成功,程序将返回true,否则为false。我需要这段代码才能真正有效因为这个功能将进入forloop,我在网站上为每个ip做所有显示。提前Thnx

P.S Ops我的意思是java / jsp我的坏哈哈

1 个答案:

答案 0 :(得分:2)

    try {
        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;
        SocketAddress sockaddr = new InetSocketAddress(addr, port);

        // Create an unbound socket
        Socket sock = new Socket();

        // This method will block no more than timeoutMs.
        // If the timeout occurs, SocketTimeoutException is thrown.
        int timeoutMs = 2000;   // 2 seconds
        sock.connect(sockaddr, timeoutMs);
    } catch (UnknownHostException e) {
    } catch (SocketTimeoutException e) {
    } catch (IOException e) {
    }