
You want to get the IP address of the current request in your ASP.NET program using the C# programming language. The UserHostAddress property is the easiest way to get a string representation of the IP address.
First, this sample code presents the Application_BeginRequest method, which is executed every time a user visits the web site. You can add it by going to Add -> Global Application Class. In Application_BeginRequest, we get the current HttpRequest, then access the UserHostAddress string property. Finally, we write it to the output and complete the request.
This ASP.NET example code gets the IP address of a request. It uses C# sample code.
Method that gets IP address [ASP.NET, C#]
using System;
using System.Web;
namespace WebApplication4
{
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();
}
}
}
Result of the application
127.0.0.1
The IP address. In this example, I ran the program on the localhost server, which is a IIS7 server on my computer. In this case, the connection is only a local connection, which means my local address was the IP address returned. If this code was run on a remote server, the IP address for my internet connection would be returned.
In this example, we acquired the current IP address of the user by invoking the UserHostAddress property. This method returns a string with numbers separated by periods. This can be directly used in a Dictionary if you need to record or special-case users by their IP addresses.
Dictionary Examples ASP.NET Tutorials