Skip to content

Commit 6cc5673

Browse files
Add validation of hostnames when starting clients
1 parent 1c631d7 commit 6cc5673

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -655,16 +655,24 @@ private bool ClientBindAndConnect()
655655
else
656656
{
657657
// This will result in an invalid endpoint if the address is a hostname.
658-
// This is handled later in the Connect method if hostname resolution is available,
658+
// This is handled later in the Connect method if hostname resolution is available
659+
// (although we still check for hostname validity to error out early if it's not),
659660
// but if not then we need to error out here.
660661
serverEndpoint = ConnectionAddressData.ParseNetworkEndpoint(ConnectionData.Address, ConnectionData.Port);
661-
#if !HOSTNAME_RESOLUTION_AVAILABLE
662+
662663
if (serverEndpoint.Family == NetworkFamily.Invalid)
663664
{
665+
#if HOSTNAME_RESOLUTION_AVAILABLE
666+
if (Uri.CheckHostName(ConnectionData.Address) != UriHostNameType.Dns)
667+
{
668+
Debug.LogError($"Provided connection address \"{ConnectionData.Address}\" is not a valid hostname.");
669+
return false;
670+
}
671+
#else
664672
Debug.LogError($"Invalid server address: {ConnectionData.Address}:{ConnectionData.Port}.");
665673
return false;
666-
}
667674
#endif
675+
}
668676
}
669677

670678
InitDriver();

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,5 +183,37 @@ public void UnityTransport_EmptySecurityStringsShouldThrow([Values("", null)] st
183183
}
184184
}
185185
}
186+
187+
#if HOSTNAME_RESOLUTION_AVAILABLE
188+
private static readonly (string, bool)[] HostnameChecks =
189+
{
190+
("localhost", true),
191+
("unity3d.com", true),
192+
("unity3d.com.", true),
193+
(string.Empty, false),
194+
("unity3d.com/test", false),
195+
("test%123.com", false),
196+
};
197+
198+
[Test]
199+
[TestCaseSource(nameof(HostnameChecks))]
200+
public void UnityTransport_HostnameValidation((string, bool) testCases)
201+
{
202+
var (hostname, isValid) = testCases;
203+
204+
UnityTransport transport = new GameObject().AddComponent<UnityTransport>();
205+
transport.Initialize();
206+
207+
if (!isValid)
208+
{
209+
LogAssert.Expect(LogType.Error, $"Provided connection address \"{hostname}\" is not a valid hostname.");
210+
}
211+
212+
transport.SetConnectionData(hostname, 4242);
213+
Assert.AreEqual(isValid, transport.StartClient());
214+
215+
transport.Shutdown();
216+
}
217+
#endif
186218
}
187219
}

0 commit comments

Comments
 (0)