Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i want login or active user ip address using javascript, ajax, c# or API.
i trying
string clientAddress = HttpContext.Current.Request.UserHostAddress;


What I have tried:

"address"

C#
string clientAddress = HttpContext.Current.Request.UserHostAddress;
Posted
Updated 19-Jun-19 2:27am
Comments
F-ES Sitecore 19-Jun-19 8:32am    
This is one of the most frequently asked questions, please do a google search before asking a question.

C#
public class SampleController : ApiController
   {
       //http://localhost:54250/API/Sample

       public string GetName()
       {
           return GetLoginUserIP();
          // return employee;
       }



       private string GetLoginUserIP(HttpRequestMessage request = null)
       {
           request = request ?? Request;

           if (request.Properties.ContainsKey("MS_HttpContext"))
           {
               return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
           }
           else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
           {
               RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
               return prop.Address;
           }
           else if (HttpContext.Current != null)
           {
               return HttpContext.Current.Request.UserHostAddress;
           }
           else
           {
               return null;
           }
       }

   }
 
Share this answer
 
I was looking for this last week. By "local IP", I assume you mean the actual local IP address, not the router address. Found these links for getting the local IP on the client side:

https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript/45549790

How to get the client IP address with Javascript only | Our Code World[^]
 
Share this answer
 
Comments
Member 14146669 19-Jun-19 8:32am    
i want public ip address. using your code im getting private ip address.
Host generally is the server, what you want is going to be in the ServerVariables collection.
One caveat to using this is that proxies and forwarders will appear here, so you may want to check for an "x-forwarded-for" header and work through it (multiple proxies will add multiple addresses)
C#
string clientAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900