I need to connect to MongoDB via SSH tunnel and the JSch port forwarding is throwing an error:
local port 127.0.0.1:27017 cannot be bound
I've to connect to MongoDB via SSH tunnel. I found the code here on stackoverflow and it solved my problem. But after few weeks, the same code stopped working. I'm unable to identify the reason for it. Also, using the same credentials that I'm using in Java code, I also tried to connect to the same via CMD using SSH -L
command and it worked properly. I'm also able to connect to MongoDB to using same credentials from NoSQLBrowser. I have tried and searched for everything on google and the problem still remains unsolved. Below is the code for it -
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
SSH_SESSION = null;
SSH_SESSION = jsch.getSession(SSH_USER, SSH_HOST, SSH_PORT);
SSH_SESSION.setPassword(SSH_PASSWORD);
SSH_SESSION.setConfig(config);
SSH_SESSION.connect();
SSH_SESSION.setPortForwardingL(27017, "localhost", 22);
MongoClient mongoClient = new MongoClient(LOCAL_HOST, LOCAL_PORT);
mongoClient.setReadPreference(ReadPreference.nearest());
MongoCursor<String> dbNames = mongoClient.listDatabaseNames().iterator();
while (dbNames.hasNext()) {
System.out.println(dbNames.next());```
I'm getting the following error on port forwarding line:-
com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:27017 cannot be bound.
at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:158)
at com.jcraft.jsch.PortWatcher.addPort(PortWatcher.java:110)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1847)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1828)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1809)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1792)
at com.schenker.boot.bootdemo.controller.TestMongoAgain.main(TestMongoAgain.java:35)
Caused by: java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:150)
... 6 more
com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:27017 is not registered.
at com.jcraft.jsch.PortWatcher.delPort(PortWatcher.java:118)
at com.jcraft.jsch.Session.delPortForwardingL(Session.java:1876)
at com.jcraft.jsch.Session.delPortForwardingL(Session.java:1865)
Also, a very strange thing that if instead of PortForwardingL
if I use PortForwardingR
, it doesn't throw any error but in the next line it gets connected to my local MongoDB. Can anyone please help me with this?