File tree Expand file tree Collapse file tree 1 file changed +28
-5
lines changed
src/Serilog.Enrichers.ClientInfo/Enrichers Expand file tree Collapse file tree 1 file changed +28
-5
lines changed Original file line number Diff line number Diff line change 11using Serilog . Core ;
22using Serilog . Events ;
3+ using System ;
4+ using System . Linq ;
35
46#if NETFULL
57
@@ -49,9 +51,7 @@ private string GetIpAddress()
4951
5052 if ( ! string . IsNullOrEmpty ( ipAddress ) )
5153 {
52- var addresses = ipAddress . Split ( ',' ) ;
53- if ( addresses . Length != 0 )
54- return addresses [ 0 ] ;
54+ return GetIpAddressFromProxy ( ipAddress ) ;
5555 }
5656
5757 return _contextAccessor . HttpContext . Request . ServerVariables [ "REMOTE_ADDR" ] ;
@@ -60,8 +60,31 @@ private string GetIpAddress()
6060#else
6161 private string GetIpAddress ( )
6262 {
63- return _contextAccessor . HttpContext . Connection . RemoteIpAddress . ToString ( ) ;
63+ var ipAddress = _contextAccessor . HttpContext . Request . Headers [ "X-forwarded-for" ] . FirstOrDefault ( ) ;
64+
65+ if ( ! string . IsNullOrEmpty ( ipAddress ) )
66+ {
67+ return GetIpAddressFromProxy ( ipAddress ) ;
68+ }
69+
70+ return _contextAccessor . HttpContext . Connection . RemoteIpAddress . ToString ( ) ;
6471 }
6572#endif
73+
74+ private string GetIpAddressFromProxy ( string proxiedIpList )
75+ {
76+ var addresses = proxiedIpList . Split ( ',' ) ;
77+
78+ if ( addresses . Length != 0 )
79+ {
80+ // If IP contains port, it will be after the last : (IPv6 uses : as delimiter and could have more of them)
81+ return addresses [ 0 ] . Contains ( ":" )
82+ ? addresses [ 0 ] . Substring ( 0 , addresses [ 0 ] . LastIndexOf ( ":" , StringComparison . Ordinal ) )
83+ : addresses [ 0 ] ;
84+ }
85+
86+ return string . Empty ;
87+ }
88+
6689 }
67- }
90+ }
You can’t perform that action at this time.
0 commit comments