资讯专栏INFORMATION COLUMN

Java 实现 Ping 命令

lastSeries / 2870人阅读

摘要:是和系统下的一个命令。也属于一个通信协议,是协议的一部分。利用命令可以检查网络是否连通。百度百科上关于的介绍写的还不错,可以参考。做这个是因为我们需要用程序下载一些资源,先提前简单判断一下是否可连通,有需要的随便拿去。

Ping是Windows、Unix和Linux系统下的一个命令。Ping也属于一个通信协议,是TCP/IP协议的一部分。利用 ping 命令可以检查网络是否连通。

百度百科上关于 Ping 的介绍写的还不错,可以参考。

尝试用Java 写了个简易的实现,代码如下:

</>复制代码

  1. package com.coder4j.main;
  2. import java.io.IOException;
  3. import java.net.InetAddress;
  4. import java.net.InetSocketAddress;
  5. import java.nio.channels.SelectionKey;
  6. import java.nio.channels.Selector;
  7. import java.nio.channels.SocketChannel;
  8. import java.util.Iterator;
  9. import java.util.LinkedList;
  10. import java.util.regex.Pattern;
  11. /**
  12. * Java 实现的简易Ping 工具
  13. *
  14. * @author Chinaxiang
  15. * @date 2015-08-11
  16. *
  17. */
  18. public class JavaPing {
  19. private static int port = 80;
  20. /**
  21. * 内部Target 类,一个实例代表一个Socket 连接
  22. */
  23. private static class Target {
  24. private InetSocketAddress address;
  25. private SocketChannel channel;
  26. private Exception failure;
  27. private long connectStart;
  28. private long connectFinish = 0;
  29. private boolean shown = false;
  30. public Target(String host) {
  31. try {
  32. address = new InetSocketAddress(InetAddress.getByName(host), port);
  33. } catch (IOException x) {
  34. failure = x;
  35. }
  36. }
  37. public void show() {
  38. String result;
  39. if (connectFinish != 0) {
  40. result = Long.toString(connectFinish - connectStart) + "ms";
  41. } else if (failure != null) {
  42. result = failure.toString();
  43. } else {
  44. result = "Timed out";
  45. }
  46. System.out.println(address + " : " + result);
  47. shown = true;
  48. }
  49. }
  50. /**
  51. * 内部Printer 类,继承自Thread ,实现对Target实例show方法的调用
  52. */
  53. private static class Printer extends Thread {
  54. private LinkedList pending = new LinkedList();
  55. public Printer() {
  56. setName("Printer");
  57. setDaemon(true);
  58. }
  59. public void add(Target t) {
  60. synchronized (pending) {
  61. pending.add(t);
  62. pending.notify();
  63. }
  64. }
  65. public void run() {
  66. try {
  67. for (;;) {
  68. Target t = null;
  69. synchronized (pending) {
  70. while (pending.size() == 0) {
  71. pending.wait();
  72. }
  73. t = pending.removeFirst();
  74. }
  75. t.show();
  76. }
  77. } catch (InterruptedException x) {
  78. return;
  79. }
  80. }
  81. }
  82. /**
  83. * 内部Connector 类,继承自Thread ,实现对Target 列表的Ping 测试
  84. */
  85. private static class Connector extends Thread {
  86. private Selector sel;
  87. private Printer printer;
  88. private LinkedList pending = new LinkedList();
  89. public Connector(Printer pr) throws IOException {
  90. printer = pr;
  91. sel = Selector.open();
  92. setName("Connector");
  93. }
  94. public void add(Target t) {
  95. SocketChannel sc = null;
  96. try {
  97. sc = SocketChannel.open();
  98. sc.configureBlocking(false);
  99. boolean connected = sc.connect(t.address);
  100. t.channel = sc;
  101. t.connectStart = System.currentTimeMillis();
  102. if (connected) {
  103. t.connectFinish = t.connectStart;
  104. sc.close();
  105. printer.add(t);
  106. } else {
  107. synchronized (pending) {
  108. pending.add(t);
  109. }
  110. sel.wakeup();
  111. }
  112. } catch (IOException x) {
  113. if (sc != null) {
  114. try {
  115. sc.close();
  116. } catch (IOException xx) {
  117. }
  118. }
  119. t.failure = x;
  120. printer.add(t);
  121. }
  122. }
  123. private void processPendingTargets() throws IOException {
  124. synchronized (pending) {
  125. while (pending.size() > 0) {
  126. Target t = pending.removeFirst();
  127. try {
  128. t.channel.register(sel, SelectionKey.OP_CONNECT, t);
  129. } catch (IOException x) {
  130. t.channel.close();
  131. t.failure = x;
  132. printer.add(t);
  133. }
  134. }
  135. }
  136. }
  137. private void processSelectedKeys() throws IOException {
  138. for (Iterator i = sel.selectedKeys().iterator(); i.hasNext();) {
  139. SelectionKey sk = i.next();
  140. i.remove();
  141. Target t = (Target) sk.attachment();
  142. SocketChannel sc = (SocketChannel) sk.channel();
  143. try {
  144. if (sc.finishConnect()) {
  145. sk.cancel();
  146. t.connectFinish = System.currentTimeMillis();
  147. sc.close();
  148. printer.add(t);
  149. }
  150. } catch (IOException x) {
  151. sc.close();
  152. t.failure = x;
  153. printer.add(t);
  154. }
  155. }
  156. }
  157. volatile boolean shutdown = false;
  158. public void shutdown() {
  159. shutdown = true;
  160. sel.wakeup();
  161. }
  162. public void run() {
  163. for (;;) {
  164. try {
  165. int n = sel.select();
  166. if (n > 0)
  167. processSelectedKeys();
  168. processPendingTargets();
  169. if (shutdown) {
  170. sel.close();
  171. return;
  172. }
  173. } catch (IOException x) {
  174. x.printStackTrace();
  175. }
  176. }
  177. }
  178. }
  179. /**
  180. * 提供对外的ping 方法,调用示例:
  181. * JavaPing.ping(new String[]{"www.baidu.com"});
  182. * JavaPing.ping(new String[]{"80", "www.baidu.com"});
  183. * JavaPing.ping(new String[]{"80", "www.baidu.com", "www.cctv.com"});
  184. *
  185. * @param args
  186. * @throws IOException
  187. * @throws InterruptedException
  188. */
  189. public static void ping(String[] args) throws IOException, InterruptedException {
  190. if (args.length < 1) {
  191. System.err.println("Usage: [port] host...");
  192. return;
  193. }
  194. int firstArg = 0;
  195. if (Pattern.matches("[0-9]+", args[0])) {
  196. port = Integer.parseInt(args[0]);
  197. firstArg = 1;
  198. }
  199. Printer printer = new Printer();
  200. printer.start();
  201. Connector connector = new Connector(printer);
  202. connector.start();
  203. LinkedList targets = new LinkedList();
  204. for (int i = firstArg; i < args.length; i++) {
  205. Target t = new Target(args[i]);
  206. targets.add(t);
  207. connector.add(t);
  208. }
  209. Thread.sleep(2000);
  210. connector.shutdown();
  211. connector.join();
  212. for (Iterator i = targets.iterator(); i.hasNext();) {
  213. Target t = i.next();
  214. if (!t.shown) {
  215. t.show();
  216. }
  217. }
  218. }
  219. /**
  220. * 非常简易的ping方法,仅仅为了判断是否可连通。
  221. *
  222. * @param host
  223. * @param port
  224. * @return
  225. */
  226. public static boolean ping(String host, int port) {
  227. InetSocketAddress address = null;
  228. try {
  229. address = new InetSocketAddress(InetAddress.getByName(host), port);
  230. return !address.isUnresolved();
  231. } catch (IOException e) {
  232. return false;
  233. }
  234. }
  235. public static void main(String[] args) throws InterruptedException, IOException {
  236. String[] arg = { "80", "www.baidu.com", "127.0.0.1", "www.cctv.com" };
  237. JavaPing.ping(arg);
  238. // /127.0.0.1:80 : 2ms
  239. // www.baidu.com/61.135.169.121:80 : 5ms
  240. // www.cctv.com/220.194.200.232:80 : 14ms
  241. boolean result = JavaPing.ping("www.baidu.com", 80);
  242. System.out.println(result);// true
  243. }
  244. }

做这个是因为我们需要用程序下载一些资源,先提前简单判断一下是否可连通,有需要的随便拿去。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65429.html

相关文章

  • 开源一个监控数据采集Agent:OpenFalcon-SuitAgent

    摘要:目前此系统仅支持类系统下使用,不支持系统什么是这是一个获取各种系统的监控数据的。监控数据上报公有的跟官方社区的思想一致采集的系统监控信息如内存等等一百多种没有任何信息其他的业务系统的监控都会打上。 OpenFalcon-SuitAgent 项目地址:github 版本说明 本系统版本划分如下 alpha:内部测试版(不建议使用于生产环境) beta:公开测试版(不建议使用于生产环境)...

    linkin 评论0 收藏0
  • 开源一个监控数据采集Agent:OpenFalcon-SuitAgent

    摘要:目前此系统仅支持类系统下使用,不支持系统什么是这是一个获取各种系统的监控数据的。监控数据上报公有的跟官方社区的思想一致采集的系统监控信息如内存等等一百多种没有任何信息其他的业务系统的监控都会打上。 OpenFalcon-SuitAgent 项目地址:github 版本说明 本系统版本划分如下 alpha:内部测试版(不建议使用于生产环境) beta:公开测试版(不建议使用于生产环境)...

    王晗 评论0 收藏0

发表评论

0条评论

lastSeries

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<