Skip to content

Commit 73f8bee

Browse files
committed
mwiede#450 use Socket.connect() with a timeout that has been supported since Java 1.4 instead of using old method of creating a separate thread and joining to that thread with timeout.
1 parent 485a0a2 commit 73f8bee

File tree

1 file changed

+14
-47
lines changed

1 file changed

+14
-47
lines changed

src/main/java/com/jcraft/jsch/Util.java

Lines changed: 14 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,13 @@
2626

2727
package com.jcraft.jsch;
2828

29-
import java.net.Socket;
3029
import java.io.File;
3130
import java.io.FileInputStream;
3231
import java.io.InputStream;
3332
import java.io.IOException;
33+
import java.net.InetSocketAddress;
34+
import java.net.Socket;
35+
import java.net.SocketTimeoutException;
3436
import java.nio.charset.Charset;
3537
import java.nio.charset.StandardCharsets;
3638
import java.util.Vector;
@@ -369,55 +371,20 @@ static boolean array_equals(byte[] foo, byte bar[]) {
369371
}
370372

371373
static Socket createSocket(String host, int port, int timeout) throws JSchException {
372-
Socket socket = null;
373-
if (timeout == 0) {
374-
try {
375-
socket = new Socket(host, port);
376-
return socket;
377-
} catch (Exception e) {
378-
String message = e.toString();
379-
throw new JSchException(message, e);
380-
}
381-
}
382-
final String _host = host;
383-
final int _port = port;
384-
final Socket[] sockp = new Socket[1];
385-
final Exception[] ee = new Exception[1];
386-
String message = "";
387-
Thread tmp = new Thread(() -> {
388-
sockp[0] = null;
389-
try {
390-
sockp[0] = new Socket(_host, _port);
391-
} catch (Exception e) {
392-
ee[0] = e;
393-
if (sockp[0] != null && sockp[0].isConnected()) {
394-
try {
395-
sockp[0].close();
396-
} catch (Exception eee) {
397-
}
398-
}
399-
sockp[0] = null;
400-
}
401-
});
402-
tmp.setName("Opening Socket " + host);
403-
tmp.start();
374+
Socket socket = new Socket();
404375
try {
405-
tmp.join(timeout);
406-
message = "timeout: ";
407-
} catch (InterruptedException eee) {
408-
}
409-
if (sockp[0] != null && sockp[0].isConnected()) {
410-
socket = sockp[0];
411-
} else {
412-
message += "socket is not established";
413-
if (ee[0] != null) {
414-
message = ee[0].toString();
376+
socket.connect(new InetSocketAddress(host, port), timeout);
377+
return socket;
378+
} catch (Exception e) {
379+
try {
380+
socket.close();
381+
} catch (Exception ignore) {
415382
}
416-
tmp.interrupt();
417-
tmp = null;
418-
throw new JSchException(message, ee[0]);
383+
384+
String message =
385+
e instanceof SocketTimeoutException ? "timeout: socket is not established" : e.toString();
386+
throw new JSchException(message, e);
419387
}
420-
return socket;
421388
}
422389

423390
static byte[] str2byte(String str, Charset encoding) {

0 commit comments

Comments
 (0)