java测试网络能ping通和telnet通
java测试网络能ping通和telnet通
package com.test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class Test {
public static void main(String[] args) {
ping("114.114.114.114");
//本地端口可以通过ipconfig查询
telnet("10.xx.xx.120", "10.xx.xx.155", 22, 5000);
}
/**
* 测试网络连通性
* @date 2022/8/17 9:32
*/
private static boolean ping(String ip) {
try {
InetAddress address = InetAddress.getByName(ip);
// if (address instanceof java.net.Inet4Address) {
// System.out.println(ip + " ipv4地址");
// } else if (address instanceof java.net.Inet6Address) {
// System.out.println(ip + " ipv6地址");
// }
if (address.isReachable(5000)) {
System.out.println("成功 - ping " + ip);
return true;
} else {
System.out.println("失败 - ping " + ip);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 测试端口连通性
* @param localHost 远程ip
* @param remoteHost 远程ip
* @param remotePort 远程端口
* @param timeout 超时时间,毫秒
* @date 2022/8/17 9:51
*/
private static boolean telnet(String localHost, String remoteHost, int remotePort, int timeout) {
Socket socket = null;
try {
InetAddress localInetAddr = InetAddress.getByName(localHost);
InetAddress remoteInetAddr = InetAddress.getByName(remoteHost);
socket = new Socket();
// 端口号设置为 0 表示在本地挑选一个可用端口进行连接,这里也可以改成自己想要测试的本地端口
SocketAddress localSocketAddr = new InetSocketAddress(localInetAddr, 0);
socket.bind(localSocketAddr);
InetSocketAddress endpointSocketAddr = new InetSocketAddress(remoteInetAddr, remotePort);
socket.connect(endpointSocketAddr, timeout);
System.out.println("成功 - telnet " + remoteHost + " " + remotePort);
return true;
} catch (IOException e) {
System.out.println("失败 - telnet " + remoteHost + " " + remotePort);
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
}
使用 Java 测试网络连通性的几种方法_轻鸿飘羽的博客-CSDN博客_java判断网络是否连通
还没有评论,来说两句吧...