java测试网络能ping通和telnet通

java测试网络能ping通和telnet通

  1. package com.test;
  2. import java.io.IOException;
  3. import java.net.InetAddress;
  4. import java.net.InetSocketAddress;
  5. import java.net.Socket;
  6. import java.net.SocketAddress;
  7. public class Test {
  8. public static void main(String[] args) {
  9. ping("114.114.114.114");
  10. //本地端口可以通过ipconfig查询
  11. telnet("10.xx.xx.120", "10.xx.xx.155", 22, 5000);
  12. }
  13. /**
  14. * 测试网络连通性
  15. * @date 2022/8/17 9:32
  16. */
  17. private static boolean ping(String ip) {
  18. try {
  19. InetAddress address = InetAddress.getByName(ip);
  20. // if (address instanceof java.net.Inet4Address) {
  21. // System.out.println(ip + " ipv4地址");
  22. // } else if (address instanceof java.net.Inet6Address) {
  23. // System.out.println(ip + " ipv6地址");
  24. // }
  25. if (address.isReachable(5000)) {
  26. System.out.println("成功 - ping " + ip);
  27. return true;
  28. } else {
  29. System.out.println("失败 - ping " + ip);
  30. }
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. return false;
  35. }
  36. /**
  37. * 测试端口连通性
  38. * @param localHost 远程ip
  39. * @param remoteHost 远程ip
  40. * @param remotePort 远程端口
  41. * @param timeout 超时时间,毫秒
  42. * @date 2022/8/17 9:51
  43. */
  44. private static boolean telnet(String localHost, String remoteHost, int remotePort, int timeout) {
  45. Socket socket = null;
  46. try {
  47. InetAddress localInetAddr = InetAddress.getByName(localHost);
  48. InetAddress remoteInetAddr = InetAddress.getByName(remoteHost);
  49. socket = new Socket();
  50. // 端口号设置为 0 表示在本地挑选一个可用端口进行连接,这里也可以改成自己想要测试的本地端口
  51. SocketAddress localSocketAddr = new InetSocketAddress(localInetAddr, 0);
  52. socket.bind(localSocketAddr);
  53. InetSocketAddress endpointSocketAddr = new InetSocketAddress(remoteInetAddr, remotePort);
  54. socket.connect(endpointSocketAddr, timeout);
  55. System.out.println("成功 - telnet " + remoteHost + " " + remotePort);
  56. return true;
  57. } catch (IOException e) {
  58. System.out.println("失败 - telnet " + remoteHost + " " + remotePort);
  59. e.printStackTrace();
  60. } finally {
  61. if (socket != null) {
  62. try {
  63. socket.close();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. }
  69. return false;
  70. }
  71. }

使用 Java 测试网络连通性的几种方法_轻鸿飘羽的博客-CSDN博客_java判断网络是否连通

发表评论

表情:
评论列表 (有 0 条评论,44人围观)

还没有评论,来说两句吧...

相关阅读