Check if the remote port is in use

I need to open open ports on a remote server. I am wondering if this is possible. I thought I would open the socket, and if it succeeds, it means that it was used ... otherwise, if I get an exception, then it will not be 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 a viable approach?

+6
java sockets
source share
2 answers

Does it need to be done in Java? There are tools for this ( Nmap ). Otherwise, your method will "work", but I'm not sure how useful this will be.

Be warned, firewalls can do some complicated things. Those that allow connections to establish but not do anything with it, so it seems that the port is open, but the firewall actually blocks all traffic. Or some ports will only be open for requests from a specific IP range, subnet, or physical device.

+3
source share

FWIW, a Java solution that I use from time to time (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); } } 
+10
source share

All Articles