Skip to content

Instantly share code, notes, and snippets.

@swapnilshrikhande
Last active December 12, 2016 15:08
Show Gist options
  • Save swapnilshrikhande/542a7f98f876a2c5e07b095d4930fb09 to your computer and use it in GitHub Desktop.
Save swapnilshrikhande/542a7f98f876a2c5e07b095d4930fb09 to your computer and use it in GitHub Desktop.
Get clients IP from the request packet.
public final class ClientIpAddress {
// CHECKSTYLE:OFF
// http://stackoverflow.com/a/11327345/131929
private static Pattern PRIVATE_ADDRESS_PATTERN = Pattern.compile(
"(^127\\.)|(^192\\.168\\.)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^::1$)|(^[fF][cCdD])",
Pattern.CANON_EQ);
// CHECKSTYLE:ON
private ClientIpAddress() {
}
/**
* Extracts the "real" client IP address from the request. It analyzes request headers
* {@code REMOTE_ADDR}, {@code X-Forwarded-For} as well as {@code Client-IP}. Optionally
* private/local addresses can be filtered in which case an empty string is returned.
*
* @param request HTTP request
* @param filterPrivateAddresses true if private/local addresses (see
* https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces and
* https://en.wikipedia.org/wiki/Unique_local_address) should be filtered i.e. omitted
* @return IP address or empty string
*/
public static String getFrom(HttpServletRequest request, boolean filterPrivateAddresses) {
String ip = request.getRemoteAddr();
String headerClientIp = request.getHeader("Client-IP");
String headerXForwardedFor = request.getHeader("X-Forwarded-For");
if (StringUtils.isEmpty(ip) && StringUtils.isNotEmpty(headerClientIp)) {
ip = headerClientIp;
} else if (StringUtils.isNotEmpty(headerXForwardedFor)) {
ip = headerXForwardedFor;
}
if (filterPrivateAddresses && isPrivateOrLocalAddress(ip)) {
return StringUtils.EMPTY;
} else {
return ip;
}
}
private static boolean isPrivateOrLocalAddress(String address) {
Matcher regexMatcher = PRIVATE_ADDRESS_PATTERN.matcher(address);
return regexMatcher.matches();
}
}
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.
// GetUserIPAddress
public static String GetUserIPAddress() {
string ReturnValue = '';
ReturnValue = ApexPages.currentPage().getHeaders().get('True-Client-IP');
if (ReturnValue == '') {
ReturnValue = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
} // get IP address when no caching (sandbox, dev, secure urls)
system.debug('USER IP ADDRESS: ' + ReturnValue);
return ReturnValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment