-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckip_client.go
More file actions
40 lines (34 loc) · 840 Bytes
/
checkip_client.go
File metadata and controls
40 lines (34 loc) · 840 Bytes
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
package nssh
import (
"fmt"
"io"
"net"
"net/http"
"strings"
)
// GetIP gets current global IP address using https://checkip.amazonaws.com/
func GetIP() (net.IP, error) {
client := http.DefaultClient
req, err := http.NewRequest("GET", "https://checkip.amazonaws.com/", nil)
if err != nil {
return nil, err
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= http.StatusBadRequest {
defer func() {
err := res.Body.Close()
if err != nil {
fmt.Println("failed to close response", err)
}
}()
return nil, fmt.Errorf("%s: %s %s", res.Status, req.Method, req.URL)
}
ip, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response from https://checkip.amazonaws.com: %w", err)
}
return net.ParseIP(strings.TrimSpace(string(ip))), nil
}