请用java语言socket下模拟实现Ping程序默认参数功能
时间: 2024-03-01 12:55:34 浏览: 110
以下是使用 Java Socket 实现 Ping 程序默认参数的示例代码:
```java
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class PingProgram {
public static void main(String[] args) {
String hostName = "localhost"; // 默认主机名
int portNumber = 80; // 默认端口号
try (Socket socket = new Socket(hostName, portNumber)) {
InetAddress address = socket.getInetAddress();
System.out.println("Pinging " + address.getHostAddress() + " with 32 bytes of data:");
// 发送 4 个 ping 请求
for (int i = 0; i < 4; i++) {
long startTime = System.currentTimeMillis();
socket.getOutputStream().write(("Ping " + i + " " + startTime + "\n").getBytes());
socket.getOutputStream().flush();
// 接收 ping 响应
byte[] buffer = new byte[1024];
int bytesRead = socket.getInputStream().read(buffer);
String response = new String(buffer, 0, bytesRead);
System.out.println("Received ping response: " + response.trim());
// 计算响应时间
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("Ping response time: " + duration + "ms");
}
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
}
```
该程序使用 Java Socket 连接到默认主机名和端口号,并发送 4 个 ping 请求。每个 ping 请求包含一个序号和发送时间戳。程序等待响应并计算响应时间。注意,该程序仅模拟了 ping 功能,而不是使用 ICMP 协议直接发送 ping 请求。
阅读全文