Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Getting user IP Address using C#
WhatsApp
Dhanasekar
9y
40.6
k
0
1
25
Blog
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.
Up Next
Get IP Address, Host Name, Domain Name in C#
Ebook Download
View all
Working with Directories in C#
Read by 17.6k people
Download Now!
Learn
View all
Membership not found