How to get Current User IP Address and Location Using Apex

Capture and persist the current user’s IP address and geographic login details using Apex. Useful for security, logging, and personalization.

Overview

This guide shows a practical Apex method to:

  • Retrieve the current session’s IP address.
  • Query LoginHistory and LoginGeo to obtain geolocation data for the session.
  • Update Account records with IP and formatted location values.

Why this matters

Recording IP and location can help with security audits, detecting suspicious logins, and tailoring experiences by region. Keep in mind privacy and data protection rules before storing geolocation data.

Step-by-step guide

1. Retrieve the user’s IP address

Use Auth.SessionManagement.getCurrentSession().get(‘SourceIp’) to fetch the current session IP. Wrap with Test.isRunningTest() checks so tests run without session data.

2. Fetch LoginHistory and LoginGeo details

Obtain the session’s LoginHistoryId, query LoginHistory to get LoginGeoId, then query LoginGeo for fields like Subdivision, PostalCode, City, and Country.

3. Update Account records

Map the IP and a formatted location string into two custom text fields (for example: User_IP_Address__c and User_Location__c).

Complete Apex example

public void updateAccountsIPandLocation(List<Account> newAccounts) {
    // Get the source IP address from the current session
    String sourceIp = !Test.isRunningTest() ? Auth.SessionManagement.getCurrentSession().get('SourceIp') : '';
    
    Set<String> historyIds = new Set<String>();
    LoginGeo currentGeo;
    // Get the current session's LoginHistoryId
    String sessionLoginId = !Test.isRunningTest() ? Auth.SessionManagement.getCurrentSession().get('LoginHistoryId') : '';
    
    // Query LoginHistory to get the LoginGeoId
    for (LoginHistory history : [SELECT Id, LoginGeoId FROM LoginHistory WHERE Id = :sessionLoginId]) {
        historyIds.add(history.LoginGeoId);
    }
    
    // Query LoginGeo to get the geographical details
    for (LoginGeo geo : [SELECT Id, Subdivision, PostalCode, City, Country FROM LoginGeo WHERE Id IN :historyIds LIMIT 1]) {
        currentGeo = geo;
    }
    
    // Update Account with IP address and location details
    if (currentGeo != null) {
        for (Account accountRec : newAccounts) {
            accountRec.User_IP_Address__c = sourceIp;
            accountRec.User_Location__c = currentGeo.Subdivision + ' ' + currentGeo.PostalCode + ' ' + currentGeo.City + ' ' + currentGeo.Country;
        }
    }
}

Best practices and caveats

  • Privacy: Ensure you have a valid business reason and legal basis to store IP/geolocation. Check GDPR/CCPA and internal policies.
  • Test coverage: Use proper Test.isRunningTest() guards and mock data when writing tests for this logic.
  • Null handling: Not every login will have LoginGeo; always check for null before updating records.
  • Limits: Queries in high-volume code should be bulkified and avoid per-record queries.

Use cases

  • Security auditing and login anomaly detection.
  • Auto-populating regional defaults or legal notices based on user location.
  • Audit trail for support and compliance.

By implementing the approach above you can reliably capture session IP and geolocation inside Salesforce and persist it on records that make sense for your org. Customize field names and formatting to fit your schema and compliance needs.

Why this matters for Salesforce admins, developers, and business users: capturing session IP and location improves security posture, aids investigations, and enables region-aware features while requiring careful attention to privacy and testing. Admins should approve fields and policies; developers should bulkify and test; business users should define acceptable uses.