-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip.go
More file actions
42 lines (34 loc) · 1.03 KB
/
Copy pathip.go
File metadata and controls
42 lines (34 loc) · 1.03 KB
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
package main
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
)
const maxIPResponseSize = 45
func getLiveIP(ctx context.Context, httpClient *http.Client) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://ifconfig.me", nil)
if err != nil {
return "", &IPCheckError{Err: fmt.Errorf("create request: %w", err)}
}
req.Header.Set("User-Agent", "curl/8.12.1")
resp, err := httpClient.Do(req)
if err != nil {
return "", &IPCheckError{Err: fmt.Errorf("reach ifconfig.me: %w", err)}
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", &IPCheckError{Err: fmt.Errorf("non-200 status: %s", resp.Status)}
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxIPResponseSize))
if err != nil {
return "", &IPCheckError{Err: fmt.Errorf("read response: %w", err)}
}
liveIP := strings.TrimSpace(string(body))
if ip := net.ParseIP(liveIP); ip == nil || ip.To4() == nil {
return "", &IPCheckError{Err: fmt.Errorf("not a valid IPv4 address: %q", liveIP)}
}
return liveIP, nil
}