给定一对主机名和端口(即www.stackoverflow.com,端口80),我希望获得与它们相关的所有IP。此外,我想将它们列入Windows Phone屏幕中的列表视图。我已经看过 ResolveHostNameAsync 类,甚至实现了它的一个例子,但我仍然没有得到如何正确使用它,因为在我的例子中,永远不会调用回调方法。
我的代码如下:
// Constructor
public StartPage() {
InitializeComponent();
ResolveHostName("www.stackoverflow.com");
}
private void ResolveHostName(String hostName) {
var endPoint = new DnsEndPoint(hostName, 80);
DeviceNetworkInformation.ResolveHostNameAsync(
endPoint,
OnNameResolved,
null
);
}
private void OnNameResolved(NameResolutionResult result) {
IPEndPoint[] endpoints = result.IPEndPoints;
// Here your address if resolved
if (endpoints != null && endpoints.Length > 0) {
var ipAddress = endpoints[0].Address;
testData.Text += ipAddress;
} else {
testData.Text += "empty";
}
}
testData 是一个TextBlock,只是为了显示第一个IP。有趣的是,甚至"空的"显示,所以我想知道回调 OnNameResolved 是否真的被调用。
有人可以提供有关如何继续的帮助吗?提前谢谢。
答案 0 :(得分:0)
我刚刚解决了我的问题。我使用了不同的方法,使用异步方法和套接字。我在StartPage构造函数中调用了这个波纹管方法, testData 显示了所需的值。
private async void getIPs() {
HostName serverHost = new HostName("www.stackoverflow.com");
var clientSocket = new Windows.Networking.Sockets.StreamSocket();
// Try to connect to the remote host
await clientSocket.ConnectAsync(serverHost, "http");
// Get the HostName as DisplayName, CanonicalName, Raw with the IpAddress.
var ipAddress = clientSocket.Information.RemoteAddress.DisplayName;
testData.Text += ipAddress;
}