When retrieving URL via HttpWebRequest, can I see the IP address of the destination server?

倖福魔咒の 提交于 2019-12-11 02:48:58

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1365586/when-retrieving-url-via-httpwebrequest-can-i-see-the-ip-address-of-the-destinat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!