function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew SteeleAndrew Steele 

Checking Trusted IP range through Apex

Hi,

Is there a way to access the trusted IP ranges through Apex and SOQL? I'm creating a visualforce application that checks if the user has specific Ip ranges set.

Thanks,
Andrew
Sumitkumar_ShingaviSumitkumar_Shingavi
Hello Andrew,

You need to do 2 things:
1. Store your Id range in a custom setting object which has numeric fields like Start1__c, Start2__c, Start3__c, Start4__c which forms Id like (Start1__c.Start2__c.Start3__c.Start4__c) and same for End Ip. so that you can easily compare.
2. You can use this code snippet to get user IP and check it against above range:
public static String GetUserIPAddress() {
 string ReturnValue = '';  
   
 // True-Client-IP has the value when the request is coming via the caching integration.
        ReturnValue = ApexPages.currentPage().getHeaders().get('True-Client-IP');
 
          // X-Salesforce-SIP has the value when no caching integration or via secure URL.
        if (ReturnValue == '' || ReturnValue == null) {
         ReturnValue = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
        } // get IP address when no caching (sandbox, dev, secure urls)
 
         if (ReturnValue == '' || ReturnValue == null) {
         ReturnValue = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
        } // get IP address from standard header if proxy in use
 
 return ReturnValue;
  
} // GetUserIPAddress
Hope this helps!
Vance Kessler 23Vance Kessler 23
This doesn't work in Lightning. Does anyone have a solution to get the User's IP address in Lightning?

Note: ApexPages.currentPage() is null for Lightning components.
Kirill_YunussovKirill_Yunussov
Yes, query AuthSession -
SELECT Id, UsersId, SourceIp FROM AuthSession