Skip to content

Commit

Permalink
Use try-with-resources
Browse files Browse the repository at this point in the history
  • Loading branch information
garydgregory committed Jul 19, 2023
1 parent 4213170 commit bcd77d4
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions src/main/java/org/apache/commons/net/bsd/RCommandClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -216,31 +216,15 @@ public void connect(final String hostname, final int port, final InetAddress loc
// port number limitations.
@Override
InputStream createErrorStream() throws IOException {
int localPort;
final Socket socket;

ServerSocket server = null;

for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort) {
try {
server = _serverSocketFactory_.createServerSocket(localPort, 1, getLocalAddress());
break; // got a socket
} catch (final SocketException e) {
continue;
}
}

if (server == null) {
throw new BindException("All ports in use.");
try (ServerSocket server = createServer()) {
_output_.write(Integer.toString(server.getLocalPort()).getBytes(StandardCharsets.UTF_8));
_output_.write(NULL_CHAR);
_output_.flush();
socket = server.accept();
}

_output_.write(Integer.toString(server.getLocalPort()).getBytes(StandardCharsets.UTF_8)); // $NON-NLS
_output_.write(NULL_CHAR);
_output_.flush();

socket = server.accept();
server.close();

if (isRemoteVerificationEnabled() && !verifyRemote(socket)) {
socket.close();
throw new IOException("Security violation: unexpected connection attempt by " + socket.getInetAddress().getHostAddress());
Expand All @@ -249,6 +233,17 @@ InputStream createErrorStream() throws IOException {
return new SocketInputStream(socket, socket.getInputStream());
}

private ServerSocket createServer() throws IOException {
for (int localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort) {
try {
return _serverSocketFactory_.createServerSocket(localPort, 1, getLocalAddress());
} catch (final SocketException e) {
continue;
}
}
throw new BindException("All ports in use.");
}

/**
* Same as <code> rcommand(localUsername, remoteUsername, command, false); </code>
*
Expand Down

0 comments on commit bcd77d4

Please sign in to comment.