From 5fc175677fb4b013845e75bf7f5a60d9b5bdc576 Mon Sep 17 00:00:00 2001 From: lidgren Date: Sat, 1 Oct 2011 10:54:25 +0000 Subject: [PATCH] NetUtility.Resolve async version added (thanks eliseegw) --- Lidgren.Network/NetUtility.cs | 76 +++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/Lidgren.Network/NetUtility.cs b/Lidgren.Network/NetUtility.cs index b1b6c0f..3197e35 100644 --- a/Lidgren.Network/NetUtility.cs +++ b/Lidgren.Network/NetUtility.cs @@ -32,6 +32,20 @@ namespace Lidgren.Network /// public static class NetUtility { + public delegate void ResolveEndPointCallback(IPEndPoint endpoint); + public delegate void ResolveAddressCallback(IPAddress adr); + + /// + /// Get IPv4 endpoint from notation (xxx.xxx.xxx.xxx) or hostname and port number (asynchronous version) + /// + public static void ResolveAsync(string ipOrHost, int port, ResolveEndPointCallback callback) + { + ResolveAsync(ipOrHost, delegate(IPAddress adr) + { + callback(new IPEndPoint(adr, port)); + }); + } + /// /// Get IPv4 endpoint from notation (xxx.xxx.xxx.xxx) or hostname and port number /// @@ -41,6 +55,68 @@ namespace Lidgren.Network return new IPEndPoint(adr, port); } + /// + /// Get IPv4 address from notation (xxx.xxx.xxx.xxx) or hostname (asynchronous version) + /// + public static void ResolveAsync(string ipOrHost, ResolveAddressCallback callback) + { + if (string.IsNullOrEmpty(ipOrHost)) + throw new ArgumentException("Supplied string must not be empty", "ipOrHost"); + + ipOrHost = ipOrHost.Trim(); + + IPAddress ipAddress = null; + if (IPAddress.TryParse(ipOrHost, out ipAddress)) + { + if (ipAddress.AddressFamily == AddressFamily.InterNetwork) + { + callback(ipAddress); + return; + } + throw new ArgumentException("This method will not currently resolve other than ipv4 addresses"); + } + + // ok must be a host name + IPHostEntry entry; + try + { + Dns.BeginGetHostEntry(ipOrHost, delegate(IAsyncResult result) + { + entry = Dns.EndGetHostEntry(result); + + if (entry == null) + { + callback(null); + return; + } + + // check each entry for a valid IP address + foreach (IPAddress ipCurrent in entry.AddressList) + { + if (ipCurrent.AddressFamily == AddressFamily.InterNetwork) + { + callback(ipCurrent); + return; + } + } + + callback(null); + }, null); + } + catch (SocketException ex) + { + if (ex.SocketErrorCode == SocketError.HostNotFound) + { + //LogWrite(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost)); + callback(null); + } + else + { + throw; + } + } + } + /// /// Get IPv4 address from notation (xxx.xxx.xxx.xxx) or hostname ///