0

I'm using this code that I found in Get public IP using DynDNS and WebRequest C#

to get the IP address. But I just get the IP Address from the server and what I need is the IP address from the user that is connected to my web application.

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);
Community
  • 1
  • 1
mcsimon
  • 351
  • 3
  • 10
  • 1
    What kind of code is this? If it's an ASP.NET application, then the client's IP address is already available in `Request.UserHostAddress` – John Saunders Jun 01 '12 at 14:41
  • This code will give you the public IP of the computer **running** the code, the code I've given below will give you the IP of the computer **requesting** your asp.net page. – Nate Jun 01 '12 at 14:43

2 Answers2

2

If you are running a web app, and you want your "client's" IP, you need to use the UserHostAddress.

var userAddress = HttpContext.Current.Request.UserHostAddress;
Nate
  • 30,286
  • 23
  • 113
  • 184
0

First obtain a context:

HttpListenerContext ctx = m_HttpListener.GetContext();

After accepting the requset, client information is availble in ctx. Use ctx to get client IP addresss:

string IP = ctx.Request.RemoteEndPoint.Address.ToString();
andr
  • 15,970
  • 10
  • 45
  • 59
mahesh
  • 1
  • 1