UserHostAddress. This method gets the IP address of the current request. It uses the UserHostAddress property in the ASP.NET framework.
Property notes. UserHostAddress is the easiest way to get a string representation of the IP address. We can use this string for recording information about requests.
This example presents the Application_BeginRequest method, which is executed every time a user visits the web site. You can add it by going to Add, and then Global Application Class.
Detail In Application_BeginRequest, we get the current HttpRequest, then access the UserHostAddress string property.
Finally We write the string value to the output. And we complete the request by calling CompleteRequest.
using System;
using System.Web;
namespace WebApplication1
{
public class Global : HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
// Get request.
HttpRequest request = base.Request;
// Get UserHostAddress property.
string address = request.UserHostAddress;
// Write to response.
base.Response.Write(address);
// Done.
base.CompleteRequest();
}
}
}127.0.0.1
The IP address. I ran the program on the localhost server. In this case, the connection is only a local connection, which means my local address was the IP address returned.
Note If this code was run on a remote server, the IP address for my internet connection would be returned.
Summary. We acquired the current IP address of the user. This yields a string with numbers separated by periods. It can be used in a Dictionary if you need to record or special-case users by IP.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 21, 2022 (edit).