@@ -62,12 +62,14 @@ public void handle(RoutingContext context) {
6262 }
6363
6464 long timestamp = System .currentTimeMillis ();
65- String remoteClient = null ;
66- try {
67- SocketAddress remoteAddress = context .request ().remoteAddress ();
68- remoteClient = getClientAddress (remoteAddress );
69- } catch (NullPointerException ex ) {
70- LOGGER .warn ("remoteAddress() throws NullPointerException" );
65+ String remoteClient = getClientAddressFromHeaders (context .request ());
66+ if (remoteClient == null ) {
67+ try {
68+ SocketAddress remoteAddress = context .request ().remoteAddress ();
69+ remoteClient = remoteAddress != null ? remoteAddress .host () : null ;
70+ } catch (NullPointerException ex ) {
71+ LOGGER .warn ("remoteAddress() throws NullPointerException" );
72+ }
7173 }
7274
7375 HttpMethod method = context .request ().method ();
@@ -78,11 +80,33 @@ public void handle(RoutingContext context) {
7880 context .next ();
7981 }
8082
81- private String getClientAddress ( SocketAddress inetSocketAddress ) {
82- if (inetSocketAddress == null ) {
83+ private static String getClientAddressFromHeaders ( HttpServerRequest request ) {
84+ if (request == null || request . headers () == null ) {
8385 return null ;
8486 }
85- return inetSocketAddress .host ();
87+ MultiMap headers = request .headers ();
88+ String value = headers .get ("X-Forwarded-For" );
89+ if (value != null && !value .isEmpty ()) {
90+ // Leftmost is the original client (RFC 7239)
91+ int comma = value .indexOf (',' );
92+ String client = comma >= 0 ? value .substring (0 , comma ).trim () : value .trim ();
93+ if (!client .isEmpty ()) {
94+ return client ;
95+ }
96+ }
97+ value = headers .get ("X-Real-IP" );
98+ if (value != null && !value .trim ().isEmpty ()) {
99+ return value .trim ();
100+ }
101+ value = headers .get ("True-Client-IP" );
102+ if (value != null && !value .trim ().isEmpty ()) {
103+ return value .trim ();
104+ }
105+ value = headers .get ("CF-Connecting-IP" );
106+ if (value != null && !value .trim ().isEmpty ()) {
107+ return value .trim ();
108+ }
109+ return null ;
86110 }
87111
88112 private void captureNoThrow (RoutingContext context , long timestamp , String remoteClient , HttpVersion version , HttpMethod method , String uri ) {
0 commit comments