Skip to content

Commit 360ffc9

Browse files
JaggerJopglombardo
andauthored
Avoid DNS lookup if provided an IPv4 or IPv6 (#221)
Co-authored-by: Peter Giacomo Lombardo <peter.lombardo@hivemq.com>
1 parent 07ce368 commit 360ffc9

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

Source/HiveMQtt/Client/Transport/TCPTransport.cs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
namespace HiveMQtt.Client.Transport;
1717

18+
using System.Data;
1819
using System.IO.Pipelines;
1920
using System.Net;
2021
using System.Net.Security;
@@ -160,17 +161,25 @@ private async Task<bool> CreateTLSConnectionAsync(Stream stream)
160161
/// <returns>A boolean representing the success or failure of the operation.</returns>
161162
public override async Task<bool> ConnectAsync(CancellationToken cancellationToken = default)
162163
{
163-
IPEndPoint ipEndPoint;
164-
var ipAddress = await LookupHostNameAsync(this.Options.Host, this.Options.PreferIPv6).ConfigureAwait(false);
164+
IPEndPoint? ipEndPoint = null;
165165

166-
// Create the IPEndPoint depending on whether it is a host name or IP address.
167-
if (ipAddress == null)
166+
if (IPAddress.TryParse(this.Options.Host, out var parsedIp))
168167
{
169-
ipEndPoint = new IPEndPoint(IPAddress.Parse(this.Options.Host), this.Options.Port);
168+
ipEndPoint = new IPEndPoint(parsedIp, this.Options.Port);
170169
}
171170
else
172171
{
173-
ipEndPoint = new IPEndPoint(ipAddress, this.Options.Port);
172+
var lookupResult = await LookupHostNameAsync(this.Options.Host, this.Options.PreferIPv6).ConfigureAwait(false);
173+
174+
if (lookupResult != null)
175+
{
176+
ipEndPoint = new IPEndPoint(lookupResult, this.Options.Port);
177+
}
178+
}
179+
180+
if (ipEndPoint == null)
181+
{
182+
throw new HiveMQttClientException("Failed to create IPEndPoint. Broker is no valid IP address or hostname.");
174183
}
175184

176185
this.Socket = new(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

0 commit comments

Comments
 (0)