给我一个基于Socket的能完成ping程序设计与实现的java代码,能自己输入ip地址
时间: 2023-12-17 19:02:52 浏览: 181
好的,以下是一个基于Socket的能完成ping程序设计与实现的Java代码,可以自己输入IP地址:
```java
import java.net.*;
public class PingClient {
public static void main(String[] args) {
try {
// 创建套接字
DatagramSocket socket = new DatagramSocket();
// 设置超时时间为1秒
socket.setSoTimeout(1000);
// 从命令行获取输入的IP地址
String ipAddress = args[0];
// 发送10个ping包
for (int i = 1; i <= 10; i++) {
// 构造ping包
String message = "Ping " + i;
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName(ipAddress);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 80);
// 发送ping包
long startTime = System.currentTimeMillis();
socket.send(packet);
// 接收ping包的回复
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
try {
socket.receive(receivePacket);
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println("Received from " + ipAddress + ": " + new String(receivePacket.getData()) + " RTT: " + timeElapsed + "ms");
} catch (SocketTimeoutException e) {
System.out.println("Request timed out.");
}
}
// 关闭套接字
socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
```
这段代码通过DatagramSocket来实现ping程序的功能,它发送了10个ping包到指定的IP地址,并且等待回复,如果在1秒内没有收到回复则认为请求超时。输出包括接收到的回复和每个ping包的往返时间。
阅读全文