sockopt_linux.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // +build linux
  2. package tcp
  3. import (
  4. "syscall"
  5. "v2ray.com/core/common/net"
  6. "v2ray.com/core/transport/internet"
  7. )
  8. const SO_ORIGINAL_DST = 80
  9. func GetOriginalDestination(conn internet.Connection) (net.Destination, error) {
  10. sysrawconn, f := conn.(syscall.Conn)
  11. if !f {
  12. return net.Destination{}, newError("unable to get syscall.Conn")
  13. }
  14. rawConn, err := sysrawconn.SyscallConn()
  15. if err != nil {
  16. return net.Destination{}, newError("failed to get sys fd").Base(err)
  17. }
  18. var dest net.Destination
  19. err = rawConn.Control(func(fd uintptr) {
  20. addr, err := syscall.GetsockoptIPv6Mreq(int(fd), syscall.IPPROTO_IP, SO_ORIGINAL_DST)
  21. if err != nil {
  22. newError("failed to call getsockopt").Base(err).WriteToLog()
  23. return
  24. }
  25. ip := net.IPAddress(addr.Multiaddr[4:8])
  26. port := uint16(addr.Multiaddr[2])<<8 + uint16(addr.Multiaddr[3])
  27. dest = net.TCPDestination(ip, net.Port(port))
  28. })
  29. if err != nil {
  30. return net.Destination{}, newError("failed to control connection").Base(err)
  31. }
  32. if !dest.IsValid() {
  33. return net.Destination{}, newError("failed to call getsockopt")
  34. }
  35. return dest, nil
  36. }