如何编写一个方法来解析作为返回IP地址的参数输入的主机名?
我搜索了一种方法,我发现这两个网站都有类似的解决方案
WP7 Mango - How to get an IP address for a given hostname
public void DnsLookup(string hostname)
{
var endpoint = new DnsEndPoint(hostname, 0);
DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnNameResolved, null);
}
private void OnNameResolved(NameResolutionResult result)
{
IPEndPoint[] endpoints = result.IPEndPoints;
// Do something with your endpoints
}
我在使用soluitons时遇到了麻烦。
我无法更改OnNameResolved的返回类型,ResolveHostNameAsync需要NameResolutionCallback。
那么如何创建一个返回IP地址的方法呢?
答案 0 :(得分:1)
鉴于此处.NET Framework的功能有限,您必须在此处编写异步方法:
public static class NetworkHelper
{
public event EventHandler<DnsLookupCompletedEventArgs> DnsLookupCompleted;
public void DnsLookupAsync(string hostname)
{
var endpoint = new DnsEndPoint(hostname, 0);
DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnNameResolved, null);
}
private void OnNameResolved(NameResolutionResult result)
{
IPEndPoint[] endpoints = result.IPEndPoints;
var args = new DnsLookupCompletedEventArgs(endpoints);
if (DnsLookupCompleted != null)
DnsLookupCompleted(this, args);
}
}
DnsLookupCompletedEventArgs
看起来像这样,所以你可以在以后处理端点:
public class DnsLookupCompletedEventArgs : EventArgs
{
public IPEndPoint[] Endpoints { get; private set; }
public DnsLookupCompletedEventArgs(IPEndPoint[] endpoints)
{
Endpoints = endpoints;
}
}