Skip to content

Instantly share code, notes, and snippets.

@vegaasen
Last active August 29, 2015 14:00
Show Gist options
  • Save vegaasen/11299618 to your computer and use it in GitHub Desktop.
Save vegaasen/11299618 to your computer and use it in GitHub Desktop.
TelnetUtils
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:vegard.aasen@telenor.com">Vegard Aasen</a>
* @since 10:40 AM
*/
public final class TelnetUtils {
private static final String HELLO = "ping";
private static final int TIMEOUT = 500;
private static final long WAIT = TimeUnit.SECONDS.toMillis(5);
public static Map<Integer, Boolean> isAlive(final String hostName, final int[] portRange) {
if (portRange.length != 2) {
throw new RuntimeException("Ops. too many port in the portRange. Expected 2, found " + portRange.length);
}
final Map<Integer, Boolean> alives = new HashMap<>();
long lastWait = 0L;
for (int i = portRange[0]; i < portRange[1]; i++) {
alives.put(i, isAlive(hostName, i));
if (lastWait == 0 || System.currentTimeMillis() > lastWait + WAIT) {
printStatus(i, portRange[1]);
lastWait = System.currentTimeMillis();
}
}
return alives;
}
public static boolean isAlive(final String hostName, final int port) {
try (final Socket pingSocket = new Socket()) {
pingSocket.connect(new InetSocketAddress(hostName, port), TIMEOUT);
pingSocket.setKeepAlive(false);
final PrintWriter out = new PrintWriter(pingSocket.getOutputStream(), true);
final BufferedReader in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()));
out.println(HELLO);
in.readLine();
pingSocket.close();
System.out.println(String.format("%s <- open", port));
return true;
} catch (final IOException e) {
return false;
}
}
private static void printStatus(final int here, final int there) {
System.out.println(String.format("%s %% - %s/%s", ((double) here * 100.0 / (double) there), here, there));
}
}
@vegaasen
Copy link
Author

Supersimple..could've used some kind of executorService or whatever, I just didnt bother 😣

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment