function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Admin DNAAdmin DNA 

get ip address in lightning component receive server erro

Hi,
i'm trying to get ip address of the client in a lightning component in a community but i receive Server error.
@AuraEnabled    
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;
} // GetUserIPAddress

Any Ideas?
Rahul Chaudhary OfficialRahul Chaudhary Official
Auth.SessionManagement.getCurrentSession().get('SourceIp')
Please try above and mark this question solved if it works.

Thank you
Raj VakatiRaj Vakati
You should be able to query AuthSession.SourceIp 
put it in @auraEnabled method inside apex controller
call backed action from lightning controller


Apex CLass
 
public class AuthSessionApexClass {
    @AuraEnabled
    public static String getIP(){
        return [Select Id ,SourceIp from AuthSession where UsersId=:UserInfo.getUserId()].SourceIp;
        
    }
}

Component 
 
<aura:component  controller="AuthSessionApexClass">
    <aura:attribute name="ipAddress" type="String" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div>
    Your IP :{!v.ipAddress}
    </div>
    
</aura:component>
 
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getIP");
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {
                component.set("v.ipAddress" ,response.getReturnValues());
            }else if (state === "ERROR"){
                
            }
        });
        $A.enqueueAction(action);
    },
})

 
Admin DNAAdmin DNA
Thank you Rahul, thankyouRaj,
I'm trying to write a test class
public static testmethod void Test1()
 {System.runAs(new User(Id = UserInfo.getUserId())){ 
     String ip = siteLeadForm.GetUserIPAddress();}

but I receive this error:
System.UnexpectedException: Current session unavailable 
Stack Trace: Class.Auth.SessionManagement.getCurrentSession: line 5, column 1 Class.siteLeadForm.GetUserIPAddress: line 18, column 1 Class.siteLeadFormTEST.Test1: line 17, column 1

do your classes also capture the community guest user ip?
Thank you in advance