如何从c#windows 8 Metro App中的HostName获取IPAddress?

时间:2012-11-21 09:13:41

标签: c# windows-8

我正在将Windows窗体类库迁移到Metro App类库。在那里有一个代码块,它从下面的主机名提供IPAddress,

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

例如:

地址:talk.google.com

ipAddress:xx.xxx.xxx.xx

但我发现Metro App System.Net中没有IPHostEntryDnsIPAddress

如果有人知道,请告诉我在windows 8 metro app中替换这些内容。

2 个答案:

答案 0 :(得分: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 :(得分:1)

选中How to resolve a hostname to an IP address in Metro/WinRT?并将'http'替换为https并尝试。

await clientSocket.ConnectAsync(serverHost, "https");