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
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

global_ips.go 1.7KB

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