Java实现Ping

阅读更多

实现方式 : 根据不同的情况可分为如下两种

    直接调用监控服务器的ping命令去测试需要监控的设备
    通过指定服务器测试能否ping通 需要监控的设备 (运用Mina实现 )

下面将给出上述的两种实现的详细过程:

一、直接调用服务器本身的ping命令

 

TestPingCmd.java
package michael.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestPingCmd {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        // 读取txt文件中的IP列表
         TestPingCmd pinger = new TestPingCmd();
        List iplist = pinger
                .getIpListFromTxt("d:/test/idc_ping_ip.txt");

        // List iplist = new ArrayList();
        // iplist.add("222.*.*.*");
        // iplist.add("222.*.*.*");
        // iplist.add("222.*.*.*");
        // iplist.add("222.*.*.*");
        // iplist.add("222.*.*.*");
        ThreadPoolExecutor executorPool = new ThreadPoolExecutor(50, 60, 60,
                TimeUnit.SECONDS, new ArrayBlockingQueue(50),
                new ThreadPoolExecutor.CallerRunsPolicy());
        long startTime = System.currentTimeMillis();
        final int maxCount = 4;
        for (final String ip : iplist) {
            executorPool.execute(new Runnable() {
                public void run() {
                    TestPingCmd pinger = new TestPingCmd();
                    Integer countSucce = pinger.doPingCmd(ip, maxCount);
                    if (null != countSucce) {
                        System.out.println("host:[ " + ip + " ] ping cout: "
                                + maxCount + " success: " + countSucce);

                    } else {
                        System.out
                                .println("host:[ " + ip + " ] ping cout null");
                    }
                }

            });
        }
        while (executorPool.getActiveCount() > 0) {
            Thread.sleep(100);
        }
        System.out.println("complete ping jobs count = " + iplist.size()
                + " , total used time(ms) = "
                + (System.currentTimeMillis() - startTime));
        executorPool.shutdown();
    }

    /**
     * @param destIp
     * @param maxCount
     * @return
     */
    public Integer doPingCmd(String destIp, int maxCount) {
        LineNumberReader input = null;
        try {
            String osName = System.getProperties().getProperty("os.name");
            String pingCmd = null;
            if (osName.startsWith("Windows")) {
                pingCmd = "cmd /c ping -n {0} {1}";
                pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
            } else if (osName.startsWith("Linux")) {
                pingCmd = "ping -c {0} {1}";
                pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
            } else {
                System.out.println("not support OS");
                return null;
            }
            Process process = Runtime.getRuntime().exec(pingCmd);
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            input = new LineNumberReader(ir);
            String line;
            List reponse = new ArrayList();

            while ((line = input.readLine()) != null) {
                if (!"".equals(line)) {
                    reponse.add(line);
                    // System.out.println("====:" + line);
                }
            }
            if (osName.startsWith("Windows")) {
                return parseWindowsMsg(reponse, maxCount);
            } else if (osName.startsWith("Linux")) {
                return parseLinuxMsg(reponse, maxCount);
            }

        } catch (IOException e) {
            System.out.println("IOException   " + e.getMessage());

        } finally {
            if (null != input) {
                try {
                    input.close();
                } catch (IOException ex) {
                    System.out.println("close error:" + ex.getMessage());

                }
            }
        }
        return null;
    }

    private int parseWindowsMsg(List reponse, int total) {
        int countTrue = 0;
        int countFalse = 0;
        for (String str : reponse) {
            if (str.startsWith("来自") || str.startsWith("Reply from")) {
                countTrue++;
            }
            if (str.startsWith("请求超时") || str.startsWith("Request timed out")) {
                countFalse++;
            }
        }
        return countTrue;
    }

    private int parseLinuxMsg(List reponse, int total) {
        int countTrue = 0;
        for (String str : reponse) {
            if (str.contains("bytes from") && str.contains("icmp_seq=")) {
                countTrue++;
            }
        }
        return countTrue;
    }

    /**
     * @param filepath
     * @return list
     */
    public List getIpListFromTxt(String filepath) {
        BufferedReader br = null;
        List iplist = new ArrayList();
        try {
            File file = new File(filepath);
            br = new BufferedReader(new FileReader(file));
            while (br.ready()) {
                String line = br.readLine();
                if (null != line && !"".equals(line)) {
                    iplist.add(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);

        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (Exception ex) {
                    ex.printStackTrace(System.out);
                }
            }
        }
        return iplist;
    }

}

 二、通过指定服务器去ping测试

 

       主要思路:利用Mina在指定的第三方服务器上运行server端,然后实现客户端和 第三方 服务器建立socket连接,发送ping任务的消息给第三方服务器,第三方服务器再把执行结果实时反馈给客户端。

       代码包括四个类:

    服务端:PingServerIoHandler.java PingServer.java
    客户端:PingClientIoHandler.java PingClient.java

 

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.MessageFormat;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class PingServerIoHandler extends IoHandlerAdapter {
    private String logId = "SERVER:: ";
    private int msgCount = 0;

    @Override
    public void exceptionCaught(IoSession pSession, Throwable pCause)
            throws Exception {
        System.out.println(logId + "发生异常:" + pCause.getLocalizedMessage());
    }

    @Override
    public void messageReceived(IoSession pSession, Object pMessage)
            throws Exception {
        String msg = String.valueOf(pMessage);
        msgCount++;
        System.out.println(logId + "收到客户端第 " + msgCount + " 条消息:" + msg);
        pSession.write(msgCount);

        if (msg.startsWith("ping")) {
            String destIp = msg.split(" ")[1];
            doPingCmd(pSession, destIp);
        }

    }

    @Override
    public void messageSent(IoSession pSession, Object pMessage)
            throws Exception {
        System.out.println(logId + "发出消息:" + pMessage);
    }

    @Override
    public void sessionClosed(IoSession pSession) throws Exception {
        System.out.println(logId + "one client closed ");
    }

    @Override
    public void sessionCreated(IoSession pSession) throws Exception {
        System.out.println(logId + "sessionCreated ");
    }

    @Override
    public void sessionIdle(IoSession pSession, IdleStatus pStatus)
            throws Exception {
        super.sessionIdle(pSession, pStatus);
    }

    @Override
    public void sessionOpened(IoSession pSession) throws Exception {
        System.out.println(logId + "sessionOpened ");
    }

    private Integer doPingCmd(IoSession pSession, String destIp) {
        LineNumberReader input = null;
        int maxCount = 4;
        try {
            String osName = System.getProperties().getProperty("os.name");
            String pingCmd = null;
            if (osName.startsWith("Windows")) {
                pingCmd = "cmd /c ping -n {0} {1}";
                pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
            } else if (osName.startsWith("Linux")) {
                pingCmd = "ping -c {0} {1}";
                pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
            } else {
                System.out.println("not support OS");
                return null;
            }
            Process process = Runtime.getRuntime().exec(pingCmd);
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            input = new LineNumberReader(ir);
            String line;

            while ((line = input.readLine()) != null) {
                if (!"".equals(line)) {
                    pSession.write(line);
                }
            }
        } catch (IOException e) {
            System.out.println("IOException   " + e.getMessage());

        } finally {
            if (null != input) {
                try {
                    input.close();
                } catch (IOException ex) {
                    System.out.println("close error:" + ex.getMessage());

                }
            }
        }
        return null;
    }
}

 PingServer.java 

 

 

 

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;


public class PingServer {

    private static final int PORT = 54321;

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast(
                "codec",
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                        .forName("UTF-8"))));
        acceptor.setHandler(new PingServerIoHandler());
        acceptor.bind(new InetSocketAddress(PORT));

        System.out.println("服务端已启动,监听端口:" + PORT);

    }

}

 

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;


public class PingClientIoHandler extends IoHandlerAdapter {

    private String logId = "CLIENT:: ";

    @Override
    public void exceptionCaught(IoSession pSession, Throwable pCause)
            throws Exception {
        System.out.println(logId + "发生异常:" + pCause.getLocalizedMessage());
    }

    @Override
    public void messageReceived(IoSession pSession, Object pMessage)
            throws Exception {
        String count = String.valueOf(pMessage);
        System.out.println(logId + "服务端收到的消息数 = " + count);
    }

    @Override
    public void messageSent(IoSession pSession, Object pMessage)
            throws Exception {
        System.out.println(logId + "发出消息:" + pMessage);
    }

    @Override
    public void sessionClosed(IoSession pSession) throws Exception {
        System.out.println(logId + "one client closed ");
    }

    @Override
    public void sessionCreated(IoSession pSession) throws Exception {
        System.out.println(logId + "sessionCreated ");
    }

    @Override
    public void sessionIdle(IoSession pSession, IdleStatus pStatus)
            throws Exception {
        super.sessionIdle(pSession, pStatus);
    }

    @Override
    public void sessionOpened(IoSession pSession) throws Exception {
        System.out.println(logId + "sessionOpened ");
    }
}


import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class PingClient {

    private static final int PORT = 54321;

    /**
     * IP列表
     * @param ipList
     */
    public void createPingClient(List ipList) {
        SocketConnector connector = new NioSocketConnector();Linux停止系统运行不关闭电源命令halt
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();

        // 设定过滤器一行一行读取数据
        chain.addLast("codec", new ProtocolCodecFilter(
                new TextLineCodecFactory(Charset.forName("UTF-8"))));

        // 注册消息处理器
        connector.setHandler(new PingClientIoHandler());
        connector.setConnectTimeoutMillis(30 * 1000L);
        // 连接服务器
        ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
                54321));
        cf.awaitUninterruptibly();
        IoSession session = cf.getSession();
        for (String ip : ipList) {
            session.write("ping " + ip);
        }
        session.getCloseFuture().awaitUninterruptibly();
        connector.dispose();
        System.out.println("-------------------");
    }

    /**
     * 控制台输入
     * @param ipList
     */
    public void createPingClient() {
        SocketConnector connector = new NioSocketConnector();

        DefaultIoFilterChainBuilder chain = connector.getFilterChain();

        // 设定过滤器一行一行读取数据
        chain.addLast("codec", new ProtocolCodecFilter(
                new TextLineCodecFactory(Charset.forName("UTF-8"))));

        // 注册消息处理器
        connector.setHandler(new PingClientIoHandler());
        connector.setConnectTimeoutMillis(30 * 1000L);
        // 连接服务器
        ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
                54321));
        cf.awaitUninterruptibly();
        IoSession session = cf.getSession();
        Scanner input = new Scanner(System.in).useDelimiter("\\r\\n");
        while (input.hasNext()) {
            String s = input.next();
            if (s.equals("quit")) {
                break;
            }
            session.write(s);
        }
        // cf.getSession().getCloseFuture().awaitUninterruptibly();
        connector.dispose();
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        PingClient tester = new PingClient();
        List iplist = new ArrayList();
        iplist.add("192.168.8.89");
        iplist.add("192.168.8.93");
        iplist.add("192.168.8.109");
        iplist.add("192.168.8.117");
        iplist.add("192.168.8.118");
        tester.createPingClient(iplist);
    }

}

你可能感兴趣的:(Java实现Ping,java,ping,linux)