TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.NET Get IP Address: UserHostAddress

This ASP.NET example code gets the IP address of a request. It uses C# sample code.

UserHostAddress. This method gets the IP address of the current request.

It uses the UserHostAddress property in the ASP.NET framework. This is the easiest way to get a string representation of the IP address.

Example. 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 the string value to the output and complete the request.

Method that gets IP address: ASP.NET, C#

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();
	}
    }
}

Result of the application

127.0.0.1

The IP address. In this example, I ran the program on the localhost server, which is one on my computer. 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 with 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 IP.

Dictionary Examples


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf