From e4acacc91ea35991b495f1a84c4568b3b06fb44b Mon Sep 17 00:00:00 2001 From: Josua Jaeger Date: Thu, 16 Jan 2025 19:53:01 +0100 Subject: [PATCH] prefer IP when provided --- .../HiveMQtt/Client/Transport/TCPTransport.cs | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Source/HiveMQtt/Client/Transport/TCPTransport.cs b/Source/HiveMQtt/Client/Transport/TCPTransport.cs index 3e014bdc..89c2ac1e 100644 --- a/Source/HiveMQtt/Client/Transport/TCPTransport.cs +++ b/Source/HiveMQtt/Client/Transport/TCPTransport.cs @@ -15,6 +15,7 @@ */ namespace HiveMQtt.Client.Transport; +using System.Data; using System.IO.Pipelines; using System.Net; using System.Net.Security; @@ -160,17 +161,25 @@ private async Task CreateTLSConnectionAsync(Stream stream) /// A boolean representing the success or failure of the operation. public override async Task ConnectAsync(CancellationToken cancellationToken = default) { - IPEndPoint ipEndPoint; - var ipAddress = await LookupHostNameAsync(this.Options.Host, this.Options.PreferIPv6).ConfigureAwait(false); + IPEndPoint? ipEndPoint = null; - // Create the IPEndPoint depending on whether it is a host name or IP address. - if (ipAddress == null) + if (IPAddress.TryParse(this.Options.Host, out var parsedIp)) { - ipEndPoint = new IPEndPoint(IPAddress.Parse(this.Options.Host), this.Options.Port); + ipEndPoint = new IPEndPoint(parsedIp, this.Options.Port); } else { - ipEndPoint = new IPEndPoint(ipAddress, this.Options.Port); + var lookupResult = await LookupHostNameAsync(this.Options.Host, this.Options.PreferIPv6).ConfigureAwait(false); + + if (lookupResult != null) + { + ipEndPoint = new IPEndPoint(lookupResult, this.Options.Port); + } + } + + if (ipEndPoint == null) + { + throw new HiveMQttClientException("Failed to create IPEndPoint. Broker is no valid IP address or hostname."); } this.Socket = new(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);