Monday, January 12, 2015

Check sever status using Socket in JAVA

In some cases, you have to check server status whether server is running or not using telnet command before executing commands on the server application. This code can be used to check whether there is a running something on the given IP and Port.

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.*;

public class Telnet {

    public static void main(String args[]) {
        try {
            String ip =  "192.168.*.*";           
            int port = 23;
            Socket s1 = new Socket(ip, port);
            InputStream is = s1.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            if (dis != null) {
                System.out.println("Connected IP : " + ip + ", Port : " + port);
            } else {
                System.out.println("Connection Invalid.");
            }

            dis.close();
            s1.close();

        } catch (Exception e) {
            System.out.println("Not Connected, check Ip and Port.");

        }

    }
}

No comments:

Post a Comment