[ACCEPTED]-Test if remote port is in use-sockets
Accepted answer
FWIW, a Java solution I use from times to 1 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);
}
}
Does this have to be done in Java? There 10 are tools for that (Nmap). Else, your method 9 will "work" but I'm not sure how 8 useful this will be.
Be warned, firewalls 7 can do some tricky things. Such as allow 6 the connections to establish but do nothing 5 with it so it appears as if the port is 4 open but the firewall is actually blocking 3 all traffic. Or, some ports will only be 2 open to requests from a certain IP range, subnet, or 1 physical device.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.