-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionManager.java
63 lines (53 loc) · 1.63 KB
/
ConnectionManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.lang.reflect.Array;
import java.util.*;
import java.net.*;
import java.io.*;
public class ConnectionManager {
private InetAddress hostAddr;
private static final int MIN_PORT = 10000;
private static final int MAX_PORT = 11000;
private int connectionPort;
ConnectionManager() throws SocketException {
hostAddr = getNextNonLoopbackAddr();
}
/**
* Credit: This code snippet was taken from :
* http://www.java2s.com/Code/Java/Network-Protocol/FindsalocalnonloopbackIPv4address.htm
*/
private InetAddress getNextNonLoopbackAddr() throws SocketException {
Enumeration<NetworkInterface> ifaceList = NetworkInterface.getNetworkInterfaces();
while ( ifaceList.hasMoreElements() ) {
NetworkInterface iface = ifaceList.nextElement();
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while ( addresses.hasMoreElements() ) {
InetAddress addr = addresses.nextElement();
if ( addr instanceof Inet4Address && !addr.isLoopbackAddress() ) {
return addr;
}
}
}
return null;
}
public ServerSocket getAvailableConnection() throws IOException {
// Generate random port
int port = MIN_PORT;
ServerSocket conn = new ServerSocket();
while ( port <= MAX_PORT ) {
try {
conn.bind(new InetSocketAddress(hostAddr, port));;
break;
} catch (IOException e) {
port++;
}
}
connectionPort = port;
conn.setReuseAddress(false);
return conn;
}
public int getConnectionPort() {
return connectionPort;
}
public String getHostName() {
return hostAddr.getHostAddress();
}
}