|
@@ -2,8 +2,10 @@ package com.xxl.job.core.util;
|
2
|
2
|
|
3
|
3
|
import org.slf4j.Logger;
|
4
|
4
|
import org.slf4j.LoggerFactory;
|
|
5
|
+import org.springframework.util.StringUtils;
|
5
|
6
|
|
6
|
7
|
import java.io.IOException;
|
|
8
|
+import java.net.InetSocketAddress;
|
7
|
9
|
import java.net.ServerSocket;
|
8
|
10
|
|
9
|
11
|
/**
|
|
@@ -15,23 +17,24 @@ public class NetUtil {
|
15
|
17
|
private static Logger logger = LoggerFactory.getLogger(NetUtil.class);
|
16
|
18
|
|
17
|
19
|
/**
|
18
|
|
- * find avaliable port
|
|
20
|
+ * find avaliable port by ip
|
19
|
21
|
*
|
20
|
22
|
* @param defaultPort
|
|
23
|
+ * @param ip
|
21
|
24
|
* @return
|
22
|
25
|
*/
|
23
|
|
- public static int findAvailablePort(int defaultPort) {
|
|
26
|
+ public static int findAvailablePort(int defaultPort,String ip) {
|
24
|
27
|
int portTmp = defaultPort;
|
25
|
28
|
while (portTmp < 65535) {
|
26
|
|
- if (!isPortUsed(portTmp)) {
|
|
29
|
+ if (!isPortUsed(portTmp,ip)) {
|
27
|
30
|
return portTmp;
|
28
|
31
|
} else {
|
29
|
32
|
portTmp++;
|
30
|
33
|
}
|
31
|
34
|
}
|
32
|
|
- portTmp = defaultPort--;
|
|
35
|
+ portTmp = --defaultPort;
|
33
|
36
|
while (portTmp > 0) {
|
34
|
|
- if (!isPortUsed(portTmp)) {
|
|
37
|
+ if (!isPortUsed(portTmp,ip)) {
|
35
|
38
|
return portTmp;
|
36
|
39
|
} else {
|
37
|
40
|
portTmp--;
|
|
@@ -41,17 +44,33 @@ public class NetUtil {
|
41
|
44
|
}
|
42
|
45
|
|
43
|
46
|
/**
|
|
47
|
+ * find avaliable port
|
|
48
|
+ *
|
|
49
|
+ * @param defaultPort
|
|
50
|
+ * @return
|
|
51
|
+ */
|
|
52
|
+ public static int findAvailablePort(int defaultPort) {
|
|
53
|
+ return findAvailablePort(defaultPort,null);
|
|
54
|
+ }
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+ /**
|
44
|
58
|
* check port used
|
45
|
59
|
*
|
46
|
60
|
* @param port
|
|
61
|
+ * @param ip 为空则为 InetAddress.anyLocalAddress()
|
47
|
62
|
* @return
|
48
|
63
|
*/
|
49
|
|
- public static boolean isPortUsed(int port) {
|
|
64
|
+ public static boolean isPortUsed(int port,String ip) {
|
50
|
65
|
boolean used = false;
|
51
|
66
|
ServerSocket serverSocket = null;
|
52
|
67
|
try {
|
53
|
|
- serverSocket = new ServerSocket(port);
|
54
|
|
- used = false;
|
|
68
|
+ if(StringUtils.isEmpty(ip)){
|
|
69
|
+ serverSocket = new ServerSocket(port);
|
|
70
|
+ }else {
|
|
71
|
+ serverSocket = new ServerSocket();
|
|
72
|
+ serverSocket.bind(new InetSocketAddress(ip,port));
|
|
73
|
+ }
|
55
|
74
|
} catch (IOException e) {
|
56
|
75
|
logger.debug(">>>>>>>>>>> xxl-job, port[{}] is in use.", port);
|
57
|
76
|
used = true;
|