如何从Windows Phone 8.1上的主机名解析IP地址?

时间:2015-07-29 20:24:57

标签: c# callback windows-phone-8.1 ip-address hostname

如何编写一个方法来解析作为返回IP地址的参数输入的主机名?

我搜索了一种方法,我发现这两个网站都有类似的解决方案

WP7 Mango - How to get an IP address for a given hostname

https://social.msdn.microsoft.com/Forums/en-US/5c07b344-be5b-4358-beb1-abea581ca2bb/how-to-resolve-a-hostname-to-an-ip-address-in-windows-phone-8?forum=wpdevelop

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地址的方法呢?

1 个答案:

答案 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;
    }
}