Reputation: 4038
I am trying to establish socket connection by local port forwarding. the flow is:
Client --> SSHhost --> TargetHost
Trying to achieve that by port forwarding but keep getting
IllegalStateException: Can't connect to rHost error.
I tested that remote host does accepts connection directly and my use case is to connect via SSHhost.
not sure where it went wrong or I am open to different approach or suggestions? Thanks.
try {
jsch.addIdentity(privateKeyPath);
session = jsch.getSession(username, hostL, port);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
java.util.Properties config = new java.util.Properties();
session.setConfig(config);
} catch (JSchException e) {
throw new RuntimeException("Failed to create Jsch Session object.", e);
}
try {
session.connect();
session.setPortForwardingL(8080, rHost, rPort);
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress(rHost, 8080), timeout);
} catch (Exception e) {
String errText = String.format("Can't connect to rHost")
throw new IllegalStateException(errText);
}
session.disconnect();
} catch (JSchException e) {
throw new RuntimeException("Error durring session connection );
}
Upvotes: 0
Views: 518
Reputation: 6006
You need to change the following line
s.connect(new InetSocketAddress(rHost, 8080), timeout);
to
s.connect(new InetSocketAddress("localhost", 8080), timeout);
Because you have actually mapped your localhost port 8080 to the remote host port when you used the method session.setPortForwardingL(8080, rHost, rPort);
You can try this code
try {
jsch.addIdentity(privateKeyPath);
session = jsch.getSession(username, hostL, port);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
session.setPortForwardingL(8080, rHost, rPort);
Socket s = new Socket();
s.connect(new InetSocketAddress("localhost", 8080), timeout);
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 2