How to get the full IP list string from X-Forwarded-For Header ?

Hi

I see there are more than 4 IPs in X-Forwarded-For header, but when I try to get the value of the header either in Assign Message or Java Call out or Java Script policy, I see always the first IP (from left), but in my case. I need the third IP in the string for some other validation purpose. How can I do this ?

appreciated your help.

Thanks

Viswa.

Hi @Viswa,

Try this in your assign message policy

<AssignVariable>
<Name>header.x-forwarded-for</Name>
<Ref>request.header.x-forwarded-for.3</Ref>
</AssignVariable>

This will fetch the 3rd ip address from this header’s values, but you need to take care of the invalid index exception which will occur if index 3 is not present.

Note: In case of multiple values, indexes have to be used. Full list cannot be fetched at once

Regards

Snehal

Hi @Viswa,

You can use the variable “request.header.x-forwarded-for.values” to get the list of values. This will return an array of values. Please refer the documentation on Variables. With this you don’t have to worry about indexes.

Hope this helps!

1 Like

Hello @snehal chakraborty,

Thank you.

Tried to get the full IP list and count in JS

var count=0,var inboundIPs = ;

for(i=1; i<=MAX_IP_COUNT; i++){

ipAddr = context.getVariable(“request.header.X-Forwarded-For.”+i);

if(ipAddr!==null && ipAddr.length>0){

//set in header if needed

context.setVariable(“request.header.ipAddr”+i,ipAddr);

//store in an array if needed for the further processing in the flow

inboundIPs[i]=ipAddr;

++count;

}

}

//Cleanup if needed

for(i=1; i <= MAX_IP_COUNT; i++){

context.removeVariable(“request.header.X-Forwarded-For.”+i);

}

This helps me to get the full list without much scope for exceptions.

Hello @Mohammed Zuber

Thank you.

Tried to implement it, but looks there is a known bug with multi value headers.

https://community.apigee.com/articles/2319/how-to-handle-multi-value-headers-in-javascript.html.

Thanks @Dino.

When I try suffixing ‘’, it worked.

inboundIPs = context.getVariable(“request.header.X-Forwarded-For.values”)+‘’;

count = context.getVariable(“request.header.X-Forwarded-For.values.count”);