IBM Worklight 6 - How would i get client IP addres

2019-09-01 08:51发布

问题:

I want to have client ip address on adapter side but i don't know what is the worklight api for that. I search for it but no luck.

I used this api on client side code which is given below

WL.Device.getNetworkInfo(function (networkInfo) {
        console.log ("Ip address of device "+networkInfo.ipAddress);
       });

It works fine and i can pass this to the adapter from client side. But i just wanted to know whether the same thing can be implemented on server side in adapter procedure.

And I also used this code which is given below

var request = WL.Server.getClientRequest();
    var userAgent = request.getHeader("User-Agent");

Can we get Ip address here using this API in adapter procedure.

回答1:

WL.Server.getClientRequest() will return a reference to HttpServletRequest Java object (http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html). You can use Java APIs to get the info you need, e.g.

var request = WL.Server.getClientRequest();
request.getRemoteAddr()
request.getRemoteHost()

Note that in case there are gateways/proxies between client and your WL server (and there most probably are) above APIs will get you info about proxies. In case you need the actual device IP you can use

var request = WL.Server.getClientRequest();
var IPAddress = request.getHeader('x-forwarded-for'); 

UPDATE:

In order to iterate over headers enumeration and get the full list of request headers use following code:

    var headers = {};

var request = WL.Server.getClientRequest();
var headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()){
    var headerName = headerNames.nextElement();
    var headerValue = request.getHeader(headerName);
    headers[headerName] = headerValue;
}