1

we are using Sitecore 9.1.1 with Sitecore JSS.

I was trying to get GeoIP location based on User's IP address.

var w = Sitecore.CES.GeoIp.Core.Lookups.LookupManager.GetWhoIsInformationByIp(ipAddress);

How can I get IP address of visitors like we get using https://whatismyipaddress.com/ site.

I tried below but not getting expected IP Address.

1.
//while this gets the ip address of the visitor making the call
  HttpContext.Current.Request.UserHostAddress;
2.
//gets the ipaddress of the machine hitting your production server              
string ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 

if (ipAddress == "" || ipAddress == null)  
{                                     
  //gets the ipaddress of your local server(localhost) during development phase                                                                         
  ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];              
}

thanks a lot in advance.

3
  • since I'm going to use Sitecore GeoIP service. can sitecore API provide me IP address also?
    – Erwin Paul
    Nov 2 '19 at 17:37
  • I dont fully understand what you're looking for. You say HttpContext.Current.Request.UserHostAddress returns the visitor's IP - isnt' that what you're after?
    – Mark Lowe
    Nov 2 '19 at 21:12
  • Check this post for more details on getting the client IP: stackoverflow.com/questions/735350/…
    – Mark Lowe
    Nov 2 '19 at 21:30
0

It can be accomplished in two steps:

  1. You need to raise a request to Sitecore to activate the Sitecore IP Geolocation service. You can refer to Sitecore Documents for the same. Set up Sitecore IP Geolocation
  2. After that use the below code to get the visitor IpAddress:
if (Tracker.Current?.Interaction?.Ip != null)
 {
    string ipAddress = new IPAddress(Tracker.Current.Interaction.Ip).ToString();
 }

Now from the IpAddress you can fetch the rest of the details like Region, Country, Post Code, Longitude and Latitude, etc. You can find the code below:

var geolocation = Sitecore.CES.GeoIp.Core.Lookups.LookupManager.GetWhoIsInformationByIp(ipAddress);
        if (geolocation != null)
        {
            var city = geolocation.City;
            var postCode = geolocation.PostalCode;
            // other details
        }

See the blog post: Sitecore Geolocation Service API

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.