66// This project is under the MIT license. See the LICENSE.md file for more details.
77
88using System . Net ;
9+ using System . Net . NetworkInformation ;
910using UnityEngine ;
1011using VoltRpc . Communication ;
1112using VoltRpc . Communication . TCP ;
@@ -32,6 +33,18 @@ public sealed class TCPCommunicationLayer : CommunicationLayer
3233 [ Tooltip ( "The out port to communicate on" ) ]
3334 public int outPort = 5556 ;
3435
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+
3548 public override Client CreateClient ( )
3649 {
3750 IPEndPoint ipEndPoint = new ( IPAddress . Loopback , inPort ) ;
@@ -50,6 +63,25 @@ public override void GetIpcSettings(out object outLocation, out object inLocatio
5063 inLocation = inPort ;
5164 assemblyLocation = null ;
5265 }
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+ }
5385 }
5486}
5587
0 commit comments