I have the following requirement:
A domain name, xxx.com, is actually followed by many iP addresses: for example:
- 1.2.3.4,
- 5.6.7.8,
- 9.10.11.12
These ip addresses all have the same website. During domain name resolution, a random ip address is assigned to you (this is DNS load balancing ).
However, if I want to access a website on a specific IP address, such as a website on 5.6.7.8, but the website is restricted to be accessible only through a domain name, directly change the domain name to an IP Address url such as http: // 5.6.7.8.
What should we do?
There are two methods:
1. Modify the Hosts file and specify xxx.com to be resolved to 5.6.7.8.
2. Use http: // 5.6.7.8:
Host: xxx.com
Because I use C # code to implement this function, I want to solve it in 2nd ways.
C # uses the HttpWebRequest class to obtain an http request. It has a Header attribute and can modify the value in the Header. However, according to MSDN, the Host identity cannot be modified in this way. If you use this method:
HttpWebRequest. Headers ["Host"] = "xxx.com ";
It throws an exception:
ArgumentException: The Host header cannot be modified directly.
Can we still meet the above requirements? The answer is yes, but the method should be changed:
The Url still uses the Domain Name:
Http://xxx.com/
Set the Proxy attribute of HttpWebRequest to the IP address you want to access, as follows:
HttpWebRequest. Proxy = new WebProxy (ip. ToString ());
The reference code is as follows (the code is from reference 1 ):
using System;using System.IO;using System.Net;namespace ConsoleApplication1{ class Program { public static void Main(string[] args) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com/Default.aspx"); System.Net.WebProxy proxy = new WebProxy("208.77.186.166", 80); request.Proxy = proxy; using (WebResponse response = request.GetResponse()) { using (TextReader reader = new StreamReader(response.GetResponseStream())) { string line; while ((line = reader.ReadLine()) != null) Console.WriteLine(line); } } } }}
In this way, the domain name request of the specified IP address is implemented.
Note: Someone has already reported to Microsoft that the host header cannot be modified. Microsoft has reported that a new Host attribute will be added to the next. Net Framewok file, so that the Host header can be modified.
Original article:
By
MicrosoftSend the message
The next release of the. NET Framework will include a new "Host" property. The value of this property will be sent as "Host" header in the HTTP request.
References:
- HttpWebRequest. Headers ["Host"] throws an unexpected exception