ip.go raw

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