2018-09-24 00:02:26 -04:00
|
|
|
// Copyright 2018 Frédéric Guillot. All rights reserved.
|
|
|
|
// Use of this source code is governed by the Apache 2.0
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package request // import "miniflux.app/http/request"
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2021-02-07 16:50:06 -05:00
|
|
|
func dropIPv6zone(address string) string {
|
|
|
|
i := strings.IndexByte(address, '%')
|
|
|
|
if i != -1 {
|
|
|
|
address = address[:i]
|
|
|
|
}
|
|
|
|
return address
|
|
|
|
}
|
|
|
|
|
2018-09-24 00:02:26 -04:00
|
|
|
// FindClientIP returns client real IP address.
|
|
|
|
func FindClientIP(r *http.Request) string {
|
|
|
|
headers := []string{"X-Forwarded-For", "X-Real-Ip"}
|
|
|
|
for _, header := range headers {
|
|
|
|
value := r.Header.Get(header)
|
|
|
|
|
|
|
|
if value != "" {
|
|
|
|
addresses := strings.Split(value, ",")
|
|
|
|
address := strings.TrimSpace(addresses[0])
|
2021-02-07 16:50:06 -05:00
|
|
|
address = dropIPv6zone(address)
|
2018-09-24 00:02:26 -04:00
|
|
|
|
|
|
|
if net.ParseIP(address) != nil {
|
|
|
|
return address
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fallback to TCP/IP source IP address.
|
2021-02-07 16:50:06 -05:00
|
|
|
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
if err != nil {
|
2018-09-24 00:02:26 -04:00
|
|
|
remoteIP = r.RemoteAddr
|
|
|
|
}
|
2021-02-07 16:50:06 -05:00
|
|
|
remoteIP = dropIPv6zone(remoteIP)
|
2018-09-24 00:02:26 -04:00
|
|
|
|
2018-11-11 19:42:30 -05:00
|
|
|
// When listening on a Unix socket, RemoteAddr is empty.
|
|
|
|
if remoteIP == "" {
|
|
|
|
remoteIP = "127.0.0.1"
|
|
|
|
}
|
|
|
|
|
2018-09-24 00:02:26 -04:00
|
|
|
return remoteIP
|
|
|
|
}
|