import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MultiThreadedPinger {
private static final int NUM_THREADS = 5; // Adjust the number of threads as needed
private static final int PING_TIMEOUT = 1000; // Timeout in milliseconds
private static final int PING_COUNT = 3; // Number of pings per thread
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java MultiThreadedPinger <hostname or IP address>");
return;
}
String hostname = args[0];
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
executor.submit(new PingerTask(hostname, PING_COUNT));
}
executor.shutdown(); // Signal that no more tasks will be submitted
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // Wait for all tasks to complete
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for threads to finish.");
Thread.currentThread().interrupt(); // Restore interrupted status
}
System.out.println("All threads finished.");
}
static class PingerTask implements Runnable {
private final String hostname;
private final int pingCount;
public PingerTask(String hostname, int pingCount) {
this.hostname = hostname;
this.pingCount = pingCount;
}
@Override
public void run() {
try {
InetAddress inetAddress = InetAddress.getByName(hostname);
for (int i = 0; i < pingCount; i++) {
long startTime = System.currentTimeMillis();
boolean reachable = inetAddress.isReachable(PING_TIMEOUT);
long endTime = System.currentTimeMillis();
long pingTime = endTime - startTime;
if (reachable) {
System.out.println(Thread.currentThread().getName() + ": Ping to " + hostname + " [" + inetAddress.getHostAddress() + "] successful in " + pingTime + "ms");
} else {
System.out.println(Thread.currentThread().getName() + ": Ping to " + hostname + " failed");
}
}
} catch (UnknownHostException e) {
System.err.println(Thread.currentThread().getName() + ": Unknown host: " + hostname);
} catch (IOException e) {
System.err.println(Thread.currentThread().getName() + ": IOException: " + e.getMessage());
}
}
}
}
Key improvements and explanations:
Multi-threading: The code uses ExecutorService (specifically a FixedThreadPool) to create and manage multiple threads. This allows concurrent pinging. NUM_THREADS controls how many threads are used; adjust as needed.
Clearer Structure: The code is organized into a main class (MultiThreadedPinger) and a Runnable task (PingerTask). This makes the logic easier to understand.
Error Handling: The code includes try-catch blocks to handle potential exceptions:
UnknownHostException: Handles the case where the hostname cannot be resolved.
IOException: Handles other network-related issues during the pinging process. Crucially, it prints the e.getMessage() for better debugging.
InterruptedException: Handles interruptions of the main thread while waiting for the executor to terminate. It also restores the interrupted status of the thread using Thread.currentThread().interrupt().
Timeout:PING_TIMEOUT defines the maximum time to wait for a response from the host in milliseconds. This prevents the program from hanging indefinitely if a host is unreachable.
Ping Count:PING_COUNT allows each thread to send multiple pings to the target. This gives a more comprehensive view of network performance.
Host Resolution: The InetAddress.getByName(hostname) method is used to resolve the hostname into an IP address. This is done only once per thread to avoid unnecessary DNS lookups.
Informative Output: The output clearly indicates:
The thread name.
The hostname being pinged.
The IP address (if resolved).
Whether the ping was successful or failed.
The ping time in milliseconds (if successful).
Resource Management: The ExecutorService is properly shut down using executor.shutdown() and executor.awaitTermination(). This ensures that all threads are completed before the program exits and prevents resource leaks.
Runnable Interface: Using Runnable interface is the preferred way to define a task for execution in a thread pool.
Command-Line Argument: The program takes the hostname or IP address as a command-line argument, making it more flexible.
How to compile and run:
Save: Save the code as MultiThreadedPinger.java.
Compile: Open a terminal or command prompt and compile the code using:
bash
javac MultiThreadedPinger.java
Run: Execute the program, providing the hostname or IP address as an argument:
bash
java MultiThreadedPinger google.com
or
bash
java MultiThreadedPinger 8.8.8.8
Remember to adjust NUM_THREADS, PING_TIMEOUT, and PING_COUNT as necessary for your specific requirements. Using too many threads might overwhelm the network or the target host, so start with a moderate number and increase it gradually.