mirror of https://github.com/alibaba/arthas.git
read cleint ip from X-Forwarded-For header. #1714
parent
013f7e9ce1
commit
154b81b2a8
@ -0,0 +1,31 @@
|
|||||||
|
package com.alibaba.arthas.tunnel.server.utils;
|
||||||
|
|
||||||
|
import io.netty.handler.codec.http.HttpHeaders;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @author hengyunabc 2021-02-26
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class HttpUtils {
|
||||||
|
|
||||||
|
public static String findClientIP(HttpHeaders headers) {
|
||||||
|
String hostStr = headers.get("X-Forwarded-For");
|
||||||
|
if (hostStr == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int index = hostStr.indexOf(',');
|
||||||
|
if (index > 0) {
|
||||||
|
hostStr = hostStr.substring(0, index);
|
||||||
|
}
|
||||||
|
return hostStr;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Integer findClientPort(HttpHeaders headers) {
|
||||||
|
String portStr = headers.get("X-Real-Port");
|
||||||
|
if (portStr != null) {
|
||||||
|
return Integer.parseInt(portStr);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.alibaba.arthas.tunnel.server.utils;
|
||||||
|
|
||||||
|
import org.assertj.core.api.Assertions;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
|
||||||
|
import io.netty.handler.codec.http.HttpHeaders;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @author hengyunabc 2021-02-26
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class HttpUtilsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test1() {
|
||||||
|
HttpHeaders headers = Mockito.mock(HttpHeaders.class);
|
||||||
|
Mockito.when(headers.get("X-Forwarded-For")).thenReturn("30.25.233.172, 11.162.179.161");
|
||||||
|
|
||||||
|
String ip = HttpUtils.findClientIP(headers);
|
||||||
|
|
||||||
|
Assertions.assertThat(ip).isEqualTo("30.25.233.172");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test2() {
|
||||||
|
HttpHeaders headers = Mockito.mock(HttpHeaders.class);
|
||||||
|
Mockito.when(headers.get("X-Forwarded-For")).thenReturn("30.25.233.172");
|
||||||
|
|
||||||
|
String ip = HttpUtils.findClientIP(headers);
|
||||||
|
|
||||||
|
Assertions.assertThat(ip).isEqualTo("30.25.233.172");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test3() {
|
||||||
|
HttpHeaders headers = Mockito.mock(HttpHeaders.class);
|
||||||
|
Mockito.when(headers.get("X-Forwarded-For")).thenReturn(null);
|
||||||
|
|
||||||
|
String ip = HttpUtils.findClientIP(headers);
|
||||||
|
|
||||||
|
Assertions.assertThat(ip).isEqualTo(null);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue