Friday, 3 February 2023

How to get IP Address of user in Salesforce apex?

 Use this code in apex class:


String ipAddress = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');


'True-Client-IP' - when the request is coming via the caching integration.


'X-Salesforce-SIP' - when the request is not via caching integration (sandbox, developer edition orgs) or via the secure Url.


ex :

public class GetIPController {

  public String ipAddress {get; set;}

    //Constructor

    public GetIPController(){    

        

        // True-Client-IP has the value when the request is coming via the caching integration.

        ipAddress = ApexPages.currentPage().getHeaders().get('True-Client-IP');

        

        // X-Salesforce-SIP has the value when no caching integration or via secure URL.

        if (ipAddress == '' || ipAddress == null) {

            ipAddress = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');

        } 

        

        // get IP address when no caching (sandbox, dev, secure urls)        

        if (ipAddress == '' || ipAddress == null) {

            ipAddress = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');

        }

        

        //get IP address from standard header if proxy in use

        //ipAddress = ApexPages.currentPage().getHeaders().get('True-Client-IP');        

    }

 } 

No comments:

Post a Comment