I have the need to discover open ports on a remote server. I'm wondering if this is possible. I was thinking I'd open a socket, and if this succeeds, it means that it's used ... otherwise, if I get an exception, then it is not used.
For example,
public boolean isActive() {
Socket s = null;
try {
s = new Socket();
s.setReuseAddress(true);
SocketAddress sa = new InetSocketAddress(this.host, this.port);
s.connect(sa, 3000);
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
}
}
}
return false;
}
is this a viable approach?
One of the biggest perks of Telnet is with a simple command you can test whether a port is open. Issuing the Telnet command telnet [domainname or ip] [port] will allow you to test connectivity to a remote host on the given port.
FWIW, a Java solution I use from times to times (better than telnet: supports timeout).
package com.acme.util;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class CheckSocket {
public static void main(String[] args) {
int exitStatus = 1 ;
if (args.length != 3) {
System.out.println("Usage: CheckSocket node port timeout");
} else {
String node = args[0];
int port = Integer.parseInt(args[1]);
int timeout = Integer.parseInt(args[2]);
Socket s = null;
String reason = null ;
try {
s = new Socket();
s.setReuseAddress(true);
SocketAddress sa = new InetSocketAddress(node, port);
s.connect(sa, timeout * 1000);
} catch (IOException e) {
if ( e.getMessage().equals("Connection refused")) {
reason = "port " + port + " on " + node + " is closed.";
};
if ( e instanceof UnknownHostException ) {
reason = "node " + node + " is unresolved.";
}
if ( e instanceof SocketTimeoutException ) {
reason = "timeout while attempting to reach node " + node + " on port " + port;
}
} finally {
if (s != null) {
if ( s.isConnected()) {
System.out.println("Port " + port + " on " + node + " is reachable!");
exitStatus = 0;
} else {
System.out.println("Port " + port + " on " + node + " is not reachable; reason: " + reason );
}
try {
s.close();
} catch (IOException e) {
}
}
}
}
System.exit(exitStatus);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With