突然对Ping命令好奇,想用Java实现一下,所以简易的写了个模仿CMD里面Ping命令的程序,贴在下面。
import java.io.IOException; import java.net.InetAddress; public class Ping { public static void main(String[] args) throws IOException, InterruptedException { InetAddress address = InetAddress.getByName(args[0]); System.out.println("正在Ping "+args[0]+" ["+address.getHostAddress()+"] 具有32字节的数据"); int flag=0; for (int i = 0; i < 4; i++) { boolean b=address.isReachable(1000); System.out.println("来自 "+address.getHostAddress()+" 的回复: "+(b ?"成功":"失败")); if(b) flag++; Thread.sleep(1000); } System.out.println(); System.out.println(address.getHostAddress()+" 的 Ping 统计信息:"); System.out.println(" 数据包:已发送 = 4, 已接收 = "+flag+" ,丢失 = "+(4-flag)+"("+(4-flag)/4*100+"% 丢失)"); } }
因为要从命令行输入要Ping的参数,所以不能在Eclipse中运行,只能在CMD中运行,运行结果如下:
Ping成功的:
Ping失败的:
时间: 2024-10-09 14:32:04