6
6
// This project is under the MIT license. See the LICENSE.md file for more details.
7
7
8
8
using System . Net ;
9
+ using System . Net . NetworkInformation ;
9
10
using UnityEngine ;
10
11
using VoltRpc . Communication ;
11
12
using VoltRpc . Communication . TCP ;
@@ -32,6 +33,18 @@ public sealed class TCPCommunicationLayer : CommunicationLayer
32
33
[ Tooltip ( "The out port to communicate on" ) ]
33
34
public int outPort = 5556 ;
34
35
36
+ public TCPCommunicationLayer ( )
37
+ {
38
+ // If ports are not available, use different ports
39
+ System . Random rnd = new System . Random ( ) ;
40
+ while ( ! CheckAvailableServerPort ( inPort ) || ! CheckAvailableServerPort ( outPort ) )
41
+ {
42
+ int port = rnd . Next ( 1024 , 65353 ) ;
43
+ inPort = port ;
44
+ outPort = port + 1 ;
45
+ }
46
+ }
47
+
35
48
public override Client CreateClient ( )
36
49
{
37
50
IPEndPoint ipEndPoint = new ( IPAddress . Loopback , inPort ) ;
@@ -50,6 +63,25 @@ public override void GetIpcSettings(out object outLocation, out object inLocatio
50
63
inLocation = inPort ;
51
64
assemblyLocation = null ;
52
65
}
66
+
67
+ private bool CheckAvailableServerPort ( int port ) {
68
+ Debug . Log ( $ "Checking Port { port } ") ;
69
+ bool isAvailable = true ;
70
+
71
+ IPGlobalProperties ipGlobalProperties = IPGlobalProperties . GetIPGlobalProperties ( ) ;
72
+ IPEndPoint [ ] tcpConnInfoArray = ipGlobalProperties . GetActiveTcpListeners ( ) ;
73
+
74
+ foreach ( IPEndPoint endpoint in tcpConnInfoArray ) {
75
+ if ( endpoint . Port == port ) {
76
+ isAvailable = false ;
77
+ break ;
78
+ }
79
+ }
80
+
81
+ Debug . Log ( $ "Port { port } available = { isAvailable } ") ;
82
+
83
+ return isAvailable ;
84
+ }
53
85
}
54
86
}
55
87
0 commit comments