How to resolve a hostname to an IP address in Metr

2019-02-19 10:22发布

问题:

I'm in the process of porting a WP7 app to Windows 8 Metro and one of the (many) conversion obstacles I've encountered is discovering an IP address based on a hostname or DNS name. The following is an example of what I was previously using in WP7:

DnsEndPoint dnsEnd = new DnsEndPoint("www.google.com", 80, AddressFamily.InterNetwork);
DeviceNetworkInformation.ResolveHostNameAsync(dnsEnd, IPLookupCallbackMethod, this);

I've searched online for a solution and browsed the Metro API, but I haven't found anything yet. Has anyone else encountered this problem with Metro/WinRT and found a solution?

回答1:

using Windows.Networking;
using Windows.Networking.Sockets;

HostName serverHost = new HostName("www.google.com");
StreamSocket clientSocket = new Windows.Networking.Sockets.StreamSocket();

// Try to connect to the remote host
await clientSocket.ConnectAsync(serverHost, "http");

// Now try the clientSocket.Information property
// e.g. clientSocket.Information.RemoteAddress
// to get the ip address

Once the clientSocket has attempted a connection, the clientSocket.Information property will be hydrated with a wealth of networking information including the remote host information including ip address. I just typed this inline so I hope there are no errors. Hope this helps! Also try this link to msdn.