TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Getting user IP Address using C#
Dhanasekar
Apr 11, 2015
39.8
k
0
1
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this blog we will learn Getting user IP Address in C#.
Tracking the users hit to the web applications is required to know the users demography. Also it is a necessary in securing our applications by restricting the odd IP address from the application server.
In most of the scenario’s the user IP address will be tracked with the last gate way by which request was forwarded. Here we will discuss about the IP Address tracking of user with the Proxy, gateway and user machine’s IP.
Example
private
static
string Fetch_UserIP()
{
string VisitorsIPAddress = string.Empty;
try
{
if
(HttpContext.Current.Request.ServerVariables[
"HTTP_X_FORWARDED_FOR"
] !=
null
)
{
VisitorsIPAddress = HttpContext.Current.Request.ServerVariables[
"HTTP_X_FORWARDED_FOR"
].ToString();
}
else
if
(HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddress = HttpContext.Current.Request.UserHostAddress;
}
}
catch
(Exception ex)
{
//Handle Exceptions
}
return
VisitorsIPAddress;
}
The above can be used to fetch the Users IP and all the gateway’s IP address.
HttpContext.Current.Request.ServerVariables[
"HTTP_X_FORWARDED_FOR"
]
will have all the details with comma separated string. The first IP is the users machine IP . The HttpContext.Current.Request.UserHostAddress will be used, whenever the
HttpContext.Current.Request.ServerVariables[
"HTTP_X_FORWARDED_FOR"
]
Doesn’t have the value.
Next Recommended Reading
Get IP Address, Host Name, Domain Name in C#