Archived
2
0
This repository has been archived on 2024-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
neko-custom/server/internal/utils/ip.go

52 lines
1.0 KiB
Go
Raw Permalink Normal View History

2020-02-10 20:13:40 +13:00
package utils
import (
"bytes"
"io"
2021-05-30 07:08:41 +12:00
"net"
2020-02-10 20:13:40 +13:00
"net/http"
2021-05-30 07:08:41 +12:00
"time"
2020-02-10 20:13:40 +13:00
)
// dig @resolver1.opendns.com ANY myip.opendns.com +short -4
2021-06-26 23:44:41 +12:00
func GetIP(serverUrl string) (string, error) {
2021-05-30 07:08:41 +12:00
tr := &http.Transport{
Proxy: nil, // ignore proxy
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 30,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 15 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
client := &http.Client{Transport: tr}
2021-06-26 23:44:41 +12:00
rsp, err := client.Get(serverUrl)
2020-02-10 20:13:40 +13:00
if err != nil {
return "", err
}
defer rsp.Body.Close()
buf, err := io.ReadAll(rsp.Body)
2020-02-10 20:13:40 +13:00
if err != nil {
return "", err
}
return string(bytes.TrimSpace(buf)), nil
}
2020-04-05 15:49:43 +12:00
2021-11-18 06:00:27 +13:00
func GetHttpRequestIP(r *http.Request, proxy bool) string {
2020-04-05 15:49:43 +12:00
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
2021-11-18 06:00:27 +13:00
if IPAddress == "" || !proxy {
2020-04-05 15:49:43 +12:00
IPAddress = r.RemoteAddr
}
return IPAddress
}