forked from go-acme/lego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
45 lines (35 loc) · 1.01 KB
/
ip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package internal
import (
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/go-acme/lego/v4/log"
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
)
const getIPURL = "https://dynamicdns.park-your-domain.com/getip"
// GetClientIP returns the client's public IP address.
// It uses namecheap's IP discovery service to perform the lookup.
func GetClientIP(ctx context.Context, client *http.Client, debug bool) (addr string, err error) {
if client == nil {
client = &http.Client{Timeout: 5 * time.Second}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, getIPURL, http.NoBody)
if err != nil {
return "", fmt.Errorf("unable to create request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer func() { _ = resp.Body.Close() }()
clientIP, err := io.ReadAll(resp.Body)
if err != nil {
return "", errutils.NewReadResponseError(req, resp.StatusCode, err)
}
if debug {
log.Println("Client IP:", string(clientIP))
}
return string(clientIP), nil
}