Retrieve Guest User IP Address with VF Page

The two standard objects: AuthSessionLoginGeo don’t store the login information of a Guest User.

Using a VF Page 

<apex:page showHeader="false" sidebar="false" controller="userIPAddressController" 
action="{!getUserIPAddress}">
 <script>
    setTimeout(function(){
        var message = '{!ip}';
        parent.postMessage(message, window.top.location.origin);         
     }, 3000);
 </script>

 <apex:form >
     {!ip}
 </apex:form>

</apex:page>

Controller


public class userIPAddressController{
    public string ip {get;set;}
    public pageReference getUserIPAddress() {
        
        // True-Client-IP has the value when the request is coming via the caching integration.
        ip = ApexPages.currentPage().getHeaders().get('True-Client-IP');
        
        // X-Salesforce-SIP has the value when no caching integration or via secure URL.
        if (ip == '' || ip == null) {
            ip = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
        } 
        
        // get IP address when no caching (sandbox, dev, secure urls)        
        if (ip == '' || ip == null) {
            ip = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
        }
         
      return null;
        
    }

}




Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach