dialer.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package socks
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. )
  7. // Dialer is used to provided the transport of the proxy
  8. type Dialer interface {
  9. Dial(string) (io.ReadWriteCloser, *AddrSpec, error)
  10. }
  11. // NetDialer is a standard TCP dialer
  12. type NetDialer struct {
  13. }
  14. // NewNetDialer creates a new dialer
  15. func NewNetDialer() Dialer {
  16. return &NetDialer{}
  17. }
  18. // Dial is a base TCP dialer
  19. func (d *NetDialer) Dial(address string) (io.ReadWriteCloser, *AddrSpec, error) {
  20. c, err := net.Dial("tcp", address)
  21. if err != nil {
  22. return nil, nil, err
  23. }
  24. local := c.LocalAddr().(*net.TCPAddr)
  25. addr := AddrSpec{IP: local.IP, Port: local.Port}
  26. return c, &addr, nil
  27. }
  28. // ConnDialer is like NetDialer but with an existing TCP dialer already created
  29. type ConnDialer struct {
  30. conn net.Conn
  31. }
  32. // NewConnDialer creates a new dialer with a already created net.conn (TCP expected)
  33. func NewConnDialer(conn net.Conn) Dialer {
  34. return &ConnDialer{
  35. conn: conn,
  36. }
  37. }
  38. // Dial is a TCP dialer but already created
  39. func (d *ConnDialer) Dial(address string) (io.ReadWriteCloser, *AddrSpec, error) {
  40. local, ok := d.conn.LocalAddr().(*net.TCPAddr)
  41. if !ok {
  42. return nil, nil, fmt.Errorf("not a tcp connection")
  43. }
  44. addr := AddrSpec{IP: local.IP, Port: local.Port}
  45. return d.conn, &addr, nil
  46. }