查找主机的IP地址

时间:2015-09-29 15:01:17

标签: c# webbrowser-control ip-address

我正在使用WebBrowser控件,当用户导航到例如http://www.google.co.uk时,我想显示用户“已连接”到的主机的IP地址。 / p>

目前,我等待DocumentComplete事件触发,然后使用Dns.GetHostEntry("http://www.google.co.uk");,但这会返回AddressList这是一个IP地址数组,而不是用户连接的实际IP至。在此示例中,返回16个IPv4地址。

如何获取用户连接的IP地址而不是所有可用的地址?

代码段:

     private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
     {
            IPHostEntry Host = Dns.GetHostEntry("http://www.google.co.uk");
            foreach(var ip in Host.AddressList)
                 Debug.WriteLine("Host address list: " + ip);
     }

1 个答案:

答案 0 :(得分:2)

在查询IP之前删除httphttps

var sample_hosts = new[] {"http://www.google.co.uk", "https://www.google.co.uk", "http://www.amazon.com"};
foreach (var host in sample_hosts)
{
    var queryhost = host.Replace("http://", "").Replace("https://", "");
    var hostEntry = Dns.GetHostEntry(queryhost);
    foreach (var ip in hostEntry.AddressList)
    {
        Console.WriteLine("IP for {0}: {1}", queryhost, ip);
    }
}

打印

IP for www.google.co.uk: 64.233.176.9
IP for www.google.co.uk: 64.233.176.9
IP for www.amazon.com: 176.32.98.166

但是既然你正在使用URL,那么你也会做类似

的事情
var url = "http://www.amazon.co.uk/My-Story-Steven-Gerrard/dp/1405923385/ref=zg_bs_books_5";
var uri = new Uri(url);
Console.WriteLine(uri.Host);

返回实际的主机:

www.amazon.co.uk