Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

global_ips.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package config
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. const (
  12. ifconfigAddress = "https://ifconfig.co/ip"
  13. ifconfigTimeout = 10 * time.Second
  14. )
  15. func getGlobalIPv4(ctx context.Context) (net.IP, error) {
  16. ip, err := fetchIP(ctx, "tcp4")
  17. if err != nil || ip.To4() == nil {
  18. return nil, fmt.Errorf("cannot find public ipv4 address: %w", err)
  19. }
  20. return ip, nil
  21. }
  22. func getGlobalIPv6(ctx context.Context) (net.IP, error) {
  23. ip, err := fetchIP(ctx, "tcp6")
  24. if err != nil || ip.To4() != nil {
  25. return nil, fmt.Errorf("cannot find public ipv6 address: %w", err)
  26. }
  27. return ip, nil
  28. }
  29. func fetchIP(ctx context.Context, network string) (net.IP, error) {
  30. dialer := &net.Dialer{FallbackDelay: -1}
  31. client := &http.Client{
  32. Jar: nil,
  33. Timeout: ifconfigTimeout,
  34. Transport: &http.Transport{
  35. DialContext: func(ctx context.Context, _, addr string) (net.Conn, error) {
  36. return dialer.DialContext(ctx, network, addr) //nolint: wrapcheck
  37. },
  38. },
  39. }
  40. req, err := http.NewRequest(http.MethodGet, ifconfigAddress, nil)
  41. if err != nil {
  42. return nil, fmt.Errorf("cannot create a request: %w", err)
  43. }
  44. resp, err := client.Do(req.WithContext(ctx))
  45. if err != nil {
  46. if resp != nil {
  47. io.Copy(io.Discard, resp.Body) //nolint: errcheck
  48. }
  49. return nil, fmt.Errorf("cannot perform a request: %w", err)
  50. }
  51. defer resp.Body.Close()
  52. respDataBytes, err := io.ReadAll(resp.Body)
  53. if err != nil {
  54. return nil, fmt.Errorf("cannot read response body: %w", err)
  55. }
  56. respData := strings.TrimSpace(string(respDataBytes))
  57. ip := net.ParseIP(respData)
  58. if ip == nil {
  59. return nil, fmt.Errorf("ifconfig.co returns incorrect IP %s", respData)
  60. }
  61. return ip, nil
  62. }