Skip to content

Commit 1a2dab6

Browse files
Add possibility of binding clients to a specific port
1 parent b8dddea commit 1a2dab6

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,12 @@ internal static NetworkEndpoint ParseNetworkEndpoint(string ip, ushort port)
245245
return endpoint;
246246
}
247247

248+
/// <summary>
249+
/// The port the client will bind to. If 0 (the default), an ephemeral port will be used.
250+
/// </summary>
251+
[SerializeField]
252+
public ushort ClientBindPort;
253+
248254
/// <summary>
249255
/// Endpoint (IP address and port) clients will connect to.
250256
/// </summary>
@@ -683,6 +689,20 @@ private bool ClientBindAndConnect()
683689
}
684690

685691
InitDriver();
692+
693+
// Don't bind yet if connecting to a hostname, since we don't know if it will resolve to IPv4 or IPv6.
694+
if (serverEndpoint.Family != NetworkFamily.Invalid && ConnectionData.ClientBindPort != 0)
695+
{
696+
var bindEndpoint = serverEndpoint.Family == NetworkFamily.Ipv6
697+
? NetworkEndpoint.AnyIpv6.WithPort(ConnectionData.ClientBindPort)
698+
: NetworkEndpoint.AnyIpv4.WithPort(ConnectionData.ClientBindPort);
699+
if (m_Driver.Bind(bindEndpoint) != 0)
700+
{
701+
Debug.LogError($"Couldn't create socket. Possibly another process is using port {ConnectionData.ClientBindPort}.");
702+
return false;
703+
}
704+
}
705+
686706
Connect(serverEndpoint);
687707

688708
return true;

com.unity.netcode.gameobjects/Tests/Editor/Transports/UnityTransportTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,20 @@ public void UnityTransport_EmptySecurityStringsShouldThrow([Values("", null)] st
184184
}
185185
}
186186

187+
[Test]
188+
public void UnityTransport_BindClientToSpecificPort()
189+
{
190+
UnityTransport transport = new GameObject().AddComponent<UnityTransport>();
191+
transport.Initialize();
192+
transport.SetConnectionData("127.0.0.1", 4242);
193+
transport.ConnectionData.ClientBindPort = 14242;
194+
195+
Assert.True(transport.StartClient());
196+
Assert.AreEqual(14242, transport.GetLocalEndpoint().Port);
197+
198+
transport.Shutdown();
199+
}
200+
187201
#if HOSTNAME_RESOLUTION_AVAILABLE
188202
private static readonly (string, bool)[] k_HostnameChecks =
189203
{

0 commit comments

Comments
 (0)