How to get ip address of current user in Lightning component

We are converting our visualforce pages to Lightning component. We were getting the ip address of the current user from visualforce page standard headers. But we cant use the same in Lightning controller.

Does anyone know any solution in getting ip address in Lightning controller other than passing parameter from visualforce page?

Answer

I also had this requirement but initially wasn’t quite sure how to get the AuthSession info recommended here. Here is the code I ended up with that returned my external IP correctly:

Apex controller:

@AuraEnabled
public static String getExternalIp() {
    Map<String,String> currentSessionAttributes = Auth.SessionManagement.getCurrentSession();
    String ip = currentSessionAttributes.get('SourceIp');
    return ip;
}

Lightning Component:

var action = component.get('c.getExternalIp');
  action.setCallback(this, function(response) {
  var state = response.getState();
  if (state === "SUCCESS") {
       console.log('External IP is: ' + response.getReturnValue());
  }
  else if (state === "INCOMPLETE") {
       alert('result incomplete');
  }
  else if (state === "ERROR") {
       var errors = response.getError();
       if (errors) {
           if (errors[0] && errors[0].message) {
                 console.log("Error message: " + errors[0].message);
           }
        } else {
            console.log("Unknown error");
            }
   }
 });

 $A.enqueueAction(action);

Attribution
Source : Link , Question Author : george thomas , Answer Author : sfsf610

Leave a Comment