如何在c# windows 8 Metro应用程序中从主机名获取IPAddress?

6

我正在将Windows窗体类库迁移到Metro应用程序类库。其中有一个代码块可以从主机名中获取IPAddress,如下所示:

IPHostEntry ipHostInfo = Dns.GetHostEntry(Address);   
IPAddress ipAddress = ipHostInfo.AddressList[0];// IPAddress.Parse(address);
IPEndPoint endPoint = new IPEndPoint(ipAddress, Port);

地址: talk.google.com

IP地址: xx.xxx.xxx.xx

但是我发现在Windows 8 Metro应用程序中的System.Net命名空间中没有IPHostEntryDnsIPAddress

如果有人知道,请告诉我Windows 8 Metro应用程序中替代这些命名空间的方法。


这里有一个相当绕的方法:http://stackoverflow.com/questions/11216625/how-to-resolve-a-hostname-to-an-ip-address-in-metro-winrt - ta.speot.is
尝试使用 Dns.GetHostByName(<服务器名称>); - GiantHornet
我已经尝试过了,它从ConnectAsync方法中退出了... - Gopinath Perumal
#ta.speot.is,我尝试使用上面的链接,但出现了异常,错误信息为:“尝试对无法访问的主机进行套接字操作。(HRESULT 异常:0x80072751)”。 - Gopinath Perumal
2个回答

2
using System.Threading.Tasks;

public async static Task<string> ResolveDNS(string remoteHostName)
    {
        if (string.IsNullOrEmpty(remoteHostName))
            return string.Empty;

        string ipAddress = string.Empty;

        try
        {
            IReadOnlyList<EndpointPair> data =
              await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0");

            if (data != null && data.Count > 0)
            {
                foreach (EndpointPair item in data)
                {
                    if (item != null && item.RemoteHostName != null &&
                                  item.RemoteHostName.Type == HostNameType.Ipv4)
                    {
                        return item.RemoteHostName.CanonicalName;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ipAddress = ex.Message;
        }

        return ipAddress;
    } 

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接