Java Telnet example : testing remote service state

In most of the cases in daily job, you must have get into some situation where you needed to telnet to a machine. Although telnet is not a secure way to access remote machine, but still it can be useful if all we want to know if the particular service port on particular machine is running or not(for example you want to check say on local ip address 192.168.110 on port 3389 the RDP service is running or not and there may be other cases)

Below, we will be showing up sample code in java which you can use the automate the process. This can also be used anywhere like if you are writing a service to report health of the multiple services, just a case.



public class JavaTelnetExample {

    private static final String RDP_SERVER = "";
    private static final int RDP_SERVER_PORT = 3389;
    private static final String HTTP_SERVER = "";
    private static final int HTTP_SERVER_PORT = 80;
    // Similar to above you can test state for number of other services on number of other machines
    public static void main(String[] args) {
        System.out.println("Rdp service status on server ip : " + RDP_SERVER + " , port : " + RDP_SERVER_PORT + " = " + isServiceRunning(RDP_SERVER, RDP_SERVER_PORT));
        System.out.println("Ssh service status on server ip : " + HTTP_SERVER + " , port : " + HTTP_SERVER_PORT + " = " + isServiceRunning(HTTP_SERVER, HTTP_SERVER_PORT));


    // If able to connect successfully, return true for service state else return false.        
    private static boolean isServiceRunning(String ip, int port) {
        try {
            TelnetClient telnetClient = new TelnetClient();
            telnetClient.connect(ip, port);
            return true;
        } catch (ConnectException e) {
            return false;
        } catch (IOException e) {
            return false;

To run this code, you can download the dependencies 'Apache Commons Net' from the depending upon build tool you are using maven/gradle or jar file

Feel free to leave comment if you get any issue or any suggestion.


Popular posts from this blog

Use environment variable in Jenkins editable email notification subject.

How i tricked IntelliJ IDEA ultimate edition to keep running even after the trial period.

How to locate element in Html 'svg' tag in Selenium 2(Webdriver)