+ Start a Discussion
Andrew SteeleAndrew Steele 

Checking Trusted IP range through Apex


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.

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.
Yes, query AuthSession -
SELECT Id, UsersId, SourceIp FROM AuthSession