Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

java - How to select network interface when connecting to SFTP with JSch

I am facing problem to create a session to a remote SFTP server by JSch:

The command i use to connect the sftp server through shell is:

sftp -o BindAddress=SOME_IP_ADDRRESS myUserName@HOST_IP_ADDR

and its working fine, but when I am trying with Java (JSch) then I am getting a timeout exception. The Java code is

/* KEY_FILE_NAME = is a file with rsa public key */
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(KEY_FILE_NAME).getFile());
JSch jsch = new JSch();
jsch.addIdentity(file.getAbsolutePath());
Properties hash = new Properties();
hash.put("StrictHostKeyChecking", "no");
logger.debug("SSh Server Host name >>" + SSH_SERVER_HOST_NAME + " || User Name >>" +  SSH_SERVER_USER_NAME);

session = jsch.getSession(SSH_SERVER_USER_NAME, SSH_SERVER_HOST_NAME);
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.setConfig(hash);
session.setPort(22);
session.setTimeout(45000);
session.connect();

The exception I am getting is :

com.jcraft.jsch.JSchException: timeout: socket is not established

I guess its coming as I am not setting the BindAddress with -o option which I am using while I am using the shell command. If that is the case then how to set the -o BindAddress parameter in JSch? Or am I doing something wrong, please suggest.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not think there's an explicit support for selecting a network interface to connect from in JSch.

But you can implement a SocketFactory interface, such as that it creates a Socket instance using the constructor overload with the localAddr:

public Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

(use 0 for the localPort)

Then pass the factory to the Session.setSocketFactory() before calling the connect() and you should be good.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...