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
I recommend that you put this in a utility class and then reference it as needed in code. A great use for this is to limit access to certain pages by IP address. This is accomplished by calling the method in the constructor of a visual force page controller (or controller extension) and then using the value that is returned to check against a list. Here is a very simple example that uses a hard coded dummy IP address :
public MyControllerExtension (ApexPages.StandardController stdController) {
// notice that the method was placed in the Util class
string UserIP = Util.GetUserIPAddress();
if (UserIP != '1.2.3.4') {
PageUnAuthEnabled = true;
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Unauthorized Access from: ' + UserIP));
} else {
PageUnAuthEnabled = false;
// insert code here for normal constructor
} // check for IP address
} // constructor
With the constructor above in place, you can now add an outputpanel to your visual force page that only gets rendered (when for PageUnAuthEnabled == true) for unauthorized users. You could also redirect them to the unauthorized page instead.