Retrieve IP Address for the Guest Users in Lightning Community

Recently, we received a requirement where we needed to track the IP address of the guest users on the Salesforce Lightning Community.

One of the ways to get the IP address of the current user in Apex is using the following method:

But this method works only for logged in users and gives an error for the guest users. We tried getting the IP address from the cookies also, but it's not a good idea because it is really not necessary that for guest users, you will get the IP address in the cookies always.

At last, we came up with the following workaround to solve this riddle:

1) Create the following apex controller (ViewIPAddressController):
 public class ViewIPAddressController{
    public String ipAddress{get; set;}

    public ViewIPAddressController(){
        //this will work if no caching is in place or
        //user is logged in via secure URL
        ipAddress = ApexPages.currentPage().getHeaders().
        //this logic will execute if proxy is in use
           ipAddress = ApexPages.currentPage().getHeaders().

2) Now, create the following Visualforce page (ViewIPAddress):
 <apex:page controller="ViewIPAddressController" showHeader="false">

3) Now, use below piece of code wherever you want to get the IP Address of the guest user, it can be any apex class or @AuraEnabled method in the Lightning Component's Controller:
String ipAddress = (new PageReference('/apex/ViewIPAddress')).
                   substringBetween('<ipAddress>', '</ipAddress>');

So, using this small workaround, we can easily implement this tedious requirement. Hope this is helpful.

Happy Coding!!


  1. Hi - thanks so much for posting this. I've been trying to figure out how to do this for a while! One question from someone who is basically not a coder. How can I use this information in a flow? Thanks!

  2. Trying this myself, the IP that is resolved is Salesforce's server rather than the client's machine. Am I missing something?

  3. Hi - Thanks for posting this. I am able to get the IP using VF page but how can we achieve it in lightning component?
    Let me know if you did this. Thank You.


Post a Comment

Popular posts from SFDC Drona

Email Alert to Parent object's email field without apex