Get IP Address In ASP.NET

In this article I will show two methods to get visitors'  IP Addresses using ASP.NET.

What is IP Address?

According to Wikipedia, An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing. Its role has been characterized as follows: "A name indicates what we seek. An address indicates where it is. A route indicates how to get there.”

There are two versions of IP address, earlier Version of IP address is IPv4 contains IP address as 32 bit number, and then because of growth of internet new version of IP is developed named IPv6 which takes 128 bit to store the IP Address.

There are different ways to get IP Address of visitor of the websites.

First Method:

First method of getting IP Address is using “HTTP_X_FORWARDED_FOR” and “REMOTE_ADDR”. Where, “X_FORWARDED_FOR” is HTTP header field for identifying originating IP Address of the client who connected to internet and “REMOTE_ADDR” Returns the IP address of the remote machine.

Code to get IP Address using Method 1:

code

Second Method:

Second method of getting IP address is using built in functionality of ASP.NET. Here we use Request property of Page Class which gets the object of HttpRequest class for the requested page. HttpRequest is sealed class which enables ASP.NET to read the HTTP values sent by client machine during the web request. We access the UserHostAddress property of HttpRequest class to get the IP Address of the visitor.

Code to get IP Address using Method 2:

code

Default.aspx

code

Call above both method in Page_Load event, as soon as page will load you will get output like this.

output

Conclusion:

This are two methods to get IP Address of the visitor of your website. There are other methods also available to get IP Address by using JavaScript and other technology.

Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all