通过 HttpWebRequest 检索 URL 时,我可以看到目标服务器的 IP 地址吗?

发布于 2024-08-03 19:18:36 字数 274 浏览 2 评论 0原文

假设我按如下方式检索 url:

string url = "http://www.somesite.com/somepage.html"
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

有没有办法可以看到目标 url 的 IP 地址? 需要单独调用吗?

谢谢

Suppose I am retrieving a url as follows:

string url = "http://www.somesite.com/somepage.html"
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

Is there a way I can see the IP address of the destination url?
Does it require a separate call?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏璃陌 2024-08-10 19:18:36

虽然Dns.GetHostEntry()可以获取服务器的IP,但如果同一主机有多个A记录,您将获取所有这些记录(也称为循环DNS)。然而,当实际连接到 Web 服务器时,客户端会选择这些 IP 之一。

似乎没有一种公开的方法可以准确找出连接时使用的 IP。我在 www.justwentdown.com 上开发我们的网络监控解决方案时发现了此信息。此信息位于 Web 响应的私有字段中,

myHttpWebResponse.ResponseStream.Connection.ServerAddress

但是,由于 ConnectionServerAddress 是私有/内部属性,因此您需要使用反射来获取值。我发现 此解决方案在这些情况下非常有用。

我已经用.NET 4.0 对其进行了测试。它有点混乱,并且可能会破坏 .NET 的未来版本,因此我建议添加单元测试。

Although Dns.GetHostEntry() can get you the IP of the server, in case there are multiple A records for the same host, you'll get them all (also known as round-robin DNS). However, when actually connecting to a web server, client picks one of those IPs.

There doesn't seem to be an exposed way to find out exactly which IP was used when connecting. I've found this information while working on our web monitoring solution at www.justwentdown.com. This info is located in a private field of the web response,

myHttpWebResponse.ResponseStream.Connection.ServerAddress

However, because Connection and ServerAddress are private/internal properties, you'll need to use reflection to get the values. I've found this solution to be very useful in those situations.

I've tested it with .NET 4.0. It's a bit messy and may break with future versions of .NET, so I'd recommend adding a unit test.

心如荒岛 2024-08-10 19:18:36

查看 System.Net.Dns 类。您可以从 获取主机的 IP 地址列表Dns.GetHostEntry() 方法。

Look at the System.Net.Dns class. You can get a list of IP addresses of the host from the Dns.GetHostEntry() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文