实现方式 : 根据不同的情况可分为如下两种
直接调用监控服务器的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<String> iplist = pinger .getIpListFromTxt("d:/test/idc_ping_ip.txt"); // List<String> iplist = new ArrayList<String>(); // 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<Runnable>(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<String> reponse = new ArrayList<String>(); 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<String> 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<String> 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<String> getIpListFromTxt(String filepath) { BufferedReader br = null; List<String> iplist = new ArrayList<String>(); 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<String> 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<String> iplist = new ArrayList<String>(); 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编程语言,结合Spring Boot、Thymeleaf和Maven等技术,实现了类似操作系统内置ping命令的功能,并且增加了端口检测的特性。下面我们将详细探讨这一项目中的关键知识点。 ...
### 使用Java实现Ping的多种方法 在日常网络管理和软件开发中,经常需要检查网络连通性。`ping`命令作为一种简单而有效的工具被广泛应用于这一领域。本文将介绍几种使用Java来实现`ping`功能的方法。 #### 方法一...
标题“java实现ping.pdf”表明本文档内容与Java编程语言相关,特别是描述了一个实现网络诊断工具“ping”的Java程序。Ping工具主要用于测试数据包是否能够通过网络到达特定的主机,并测量往返时间(Round-Trip Time,...
资源包含:课程报告word+源码 编程实现PING的服务器端和客户端,实现操作系统提供的ping命令的类似功能。详细介绍参考:https://blog.csdn.net/sheziqiong/article/details/127039936
在Java编程中,我们不能直接使用内置的库来实现ping功能,因为Java标准库并不包含这样的功能。但是,我们可以借助第三方库如jpcap(Java Packet Capture)来实现这个功能。 jpcap是一个Java库,它提供了对网络接口...
- **`TestPingCmd`类**:这是整个程序的核心类,它包含了一些关键的方法来实现Ping功能。 - `main(String[] args)`方法:程序入口点,用于初始化并启动多线程处理任务。 - `getIpListFromTxt(String filename)`...
一段JAVA代码 实现ping功能 import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.SocketChannel;
总的来说,理解Java实现ping程序涉及到的知识点包括:网络基础知识、ICMP协议、Java套接字编程、UDP数据包的封装与解封,以及可能的JNI技术。通过这个过程,开发者可以深入理解网络通信的底层机制。
java中ping命令ping工具类(循环ping) java ping ip ping命令 ping工具类 支持linux和windows等所有平台 Ping是Windows下的一个命令 在Unix和Linux下也有这个命令。 ping也属于一个通信协议,是TCP/IP协议的一部分 ...
自动运维,只要把要PING的IP放在C盘的ip.txt中,格式每行一个IP地址即可。运行程序后,控制台会输出结果,显示通或者不通,也会把结果输出到C盘的result.txt,里面包括每个IP是否通,并且有哪一个日期时间去ping的。...
Ping程序是使用得比较多的用于测试网络连通性的程序。Ping程序基于ICMP协议,使用ICMP的回送请求和回送应答来工作。ICMP是基于IP的一个协议,ICMP包通过IP的封装之后传递。
设计服务器 PingServer 程序和客户端 PingClient 程序,使用 Java 网络编程中提供的 DatagramSocket,DatagramPacket,InetAddress 类及其内置方法实现服务器和客户端之间的 UDP 通信及数据报相关内容的显示,同时在...
Java实现ping功能主要涉及到对操作系统命令的调用和并发处理。在Java中,可以通过执行操作系统命令来实现ping操作,这通常使用`Runtime.getRuntime().exec()`或`ProcessBuilder`类来完成。下面详细解释这两种实现...
在Java编程语言中,实现ping功能通常涉及到网络通信和套接字编程。ping命令在网络中主要用于检查网络连接的可达性,其工作原理是发送ICMP(Internet Control Message Protocol)回显请求报文到目标主机,然后接收...
本文将深入探讨基于Socket实现Ping功能的源代码,涉及到的主要知识点包括Socket编程、原始套接字(SOCK_RAW)以及ICMP(Internet Control Message Protocol)协议。 首先,我们需要理解什么是Socket。Socket是操作...
3. **Java实现Ping**: - **Java ICMP库**:Java标准库并不直接支持ICMP,但可以借助第三方库如JICMP或JPing来实现。 - **Socket方式**:另一种方法是通过创建Socket并尝试连接到目标IP,虽然这不是真正的ICMP ...
【标题】"计网课设_Java实现简单的PING操作"涉及的主要知识点是计算机网络中的ICMP协议和Java编程语言的应用。在计算机网络中,PING是一个用于检查网络连接和数据包传输的基本工具,它基于Internet控制报文协议...
下面将详细解释基于UDP的PING实现以及相关的Java编程知识。 首先,UDP是传输层的一种无连接协议,它不提供诸如确认、流量控制或重传等服务,因此相对于TCP,UDP更适合于对实时性要求高但可以容忍数据丢失的应用场景...