获取请求的客户端地址
(supportVar bool)
| 1202 | |
| 1203 | // 获取请求的客户端地址 |
| 1204 | func (this *HTTPRequest) requestRemoteAddr(supportVar bool) string { |
| 1205 | if len(this.lnRemoteAddr) > 0 { |
| 1206 | return this.lnRemoteAddr |
| 1207 | } |
| 1208 | |
| 1209 | if supportVar && len(this.remoteAddr) > 0 { |
| 1210 | return this.remoteAddr |
| 1211 | } |
| 1212 | |
| 1213 | if supportVar && |
| 1214 | this.web.RemoteAddr != nil && |
| 1215 | this.web.RemoteAddr.IsOn && |
| 1216 | !this.web.RemoteAddr.IsEmpty() { |
| 1217 | if this.web.RemoteAddr.HasValues() { // multiple values |
| 1218 | for _, value := range this.web.RemoteAddr.Values() { |
| 1219 | var remoteAddr = this.Format(value) |
| 1220 | if len(remoteAddr) > 0 && net.ParseIP(remoteAddr) != nil { |
| 1221 | this.remoteAddr = remoteAddr |
| 1222 | return remoteAddr |
| 1223 | } |
| 1224 | } |
| 1225 | } else { // single value |
| 1226 | var remoteAddr = this.Format(this.web.RemoteAddr.Value) |
| 1227 | if len(remoteAddr) > 0 && net.ParseIP(remoteAddr) != nil { |
| 1228 | this.remoteAddr = remoteAddr |
| 1229 | return remoteAddr |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | // 如果是从Header中读取,则直接返回原始IP |
| 1234 | if this.web.RemoteAddr.Type == serverconfigs.HTTPRemoteAddrTypeRequestHeader { |
| 1235 | var remoteAddr = this.RawReq.RemoteAddr |
| 1236 | host, _, err := net.SplitHostPort(remoteAddr) |
| 1237 | if err == nil { |
| 1238 | this.remoteAddr = host |
| 1239 | return host |
| 1240 | } else { |
| 1241 | return remoteAddr |
| 1242 | } |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | // X-Forwarded-For |
| 1247 | var forwardedFor = this.RawReq.Header.Get("X-Forwarded-For") |
| 1248 | if len(forwardedFor) > 0 { |
| 1249 | commaIndex := strings.Index(forwardedFor, ",") |
| 1250 | if commaIndex > 0 { |
| 1251 | forwardedFor = forwardedFor[:commaIndex] |
| 1252 | } |
| 1253 | if net.ParseIP(forwardedFor) != nil { |
| 1254 | if supportVar { |
| 1255 | this.remoteAddr = forwardedFor |
| 1256 | } |
| 1257 | return forwardedFor |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | // Real-IP |
no test coverage detected