问题
I Use this code to get the public IP-address (thanks to this post How to get the IP address of the server on which my C# application is running on?):
public static string GetPublicIP()
{
try
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
{
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
catch (Exception ex)
{
return "127.0.0.1";
}
}
But no matter who that access my website, they all get the same IP, and it is the server public IP, not the current user's IP.
Is it possible to run the WebRequest in context of the current user, not as the server?
Or is the problem that I run this function inside App_Code so that the current user Request is not available, instead it use the server context?
Please help!
回答1:
Since you are making the request from the server you will get the server's IP address.
I am not sure what sort of service you have. In the case of a WCF service, you can grab the IP address from the IncomingMessageProperties of the OperationContext object for the request. See an example here: Get the Client’s Address in WCF
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetAddressAsString();
}
public class MyService : IMyService
{
public string GetAddressAsString()
{
RemoteEndpointMessageProperty clientEndpoint =
OperationContext.Current.IncomingMessageProperties[
RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
return String.Format(
"{0}:{1}",
clientEndpoint.Address, clientEndpoint.Port);
}
}
回答2:
I am guessing this code is running on a web server - that you've got a page that let's clients check their IP address? If so, I suspect you've got confused. If not, please elaborate on where this is running.
If the code above is running on a server, then you will always get that server's public IP address if you make a call to a remote server and ask "what is the ip address this request came from" - which is what your code sample is doing.
If you want the IP address of the clients calling you - assuming you are a web application, then you should look at HttpWebRequest.UserHostAddress, altrhough be aware that this is not foolproof. Have a look here for more info.
回答3:
This is supposed to happen, the code is running on your machine so you get your own IP address. To get something from the user, you must check the headers sent by your users, specifically the REMOTE_ADDR header.
You can probably use Request.ServerVariables["REMOTE_ADDR"] in your code somewhere.
来源:https://stackoverflow.com/questions/10597655/get-public-ip-using-dyndns-and-webrequest-c-sharp