How to Get Current User IP Address and Location Using Apex

Capture the current user’s IP address and location in Apex using Auth.SessionManagement, LoginHistory and LoginGeo. Update records (for example, Account) with IP and formatted location for security, auditing, or personalization.

Overview

Capturing a user’s IP address and geographic login information can help with security audits, compliance, fraud detection, and personalized experiences. In Salesforce, you can access session details via Auth.SessionManagement, and enrich them using the LoginHistory and LoginGeo objects. This guide walks through a reusable Apex method that retrieves the source IP, fetches geo details, and updates Account records with the information.

Step-by-step guide

1. Retrieve the user’s IP address

Use Auth.SessionManagement.getCurrentSession().get(‘SourceIp’) to get the current session IP. Wrap this with a Test.isRunningTest() check to avoid nulls during unit tests.

2. Fetch LoginHistory and LoginGeo

Get the LoginHistoryId from the current session, then query LoginHistory to obtain LoginGeoId. Finally query LoginGeo to retrieve fields like Subdivision, PostalCode, City and Country.

3. Update target records (Account example)

With the IP and geo details available, update your records. In this example we set two custom text fields on Account: User_IP_Address__c and User_Location__c.

Key code snippet

public void updateAccountsIPandLocation(List newAccounts) {
    // Get the source IP address from the current session
    String sourceIp = !Test.isRunningTest() ? Auth.SessionManagement.getCurrentSession().get('SourceIp') : '';
    
    Set historyIds = new Set();
    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 & considerations

  • Always include Test.isRunningTest() guards so your unit tests don’t rely on live session data.
  • Consider null checks for LoginGeo fields before concatenation to avoid ‘null’ strings.
  • Respect privacy and compliance: verify whether storing IP/location data is allowed for your org and region.
  • Limit DML: if updating records, batch or bulkify your approach according to transaction size.

Use cases

  • Security monitoring and audit trails.
  • Risk-based authentication or fraud detection workflows.
  • Personalized UI/content based on user location.

By implementing this method you can enrich records with session-level IP and geo information to support security, analytics, and personalization scenarios in Salesforce. Adjust fields and logic as needed for your org’s data model and compliance requirements.

Why this matters

Salesforce admins and developers gain a simple, code-first approach to capture session-level context. This helps teams investigate incidents, tailor user experiences, and meet governance requirements without heavy integration overhead.