hub_linux.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // +build linux
  2. package udp
  3. import (
  4. "net"
  5. "syscall"
  6. v2net "v2ray.com/core/common/net"
  7. )
  8. func SetOriginalDestOptions(fd int) error {
  9. if err := syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
  10. return err
  11. }
  12. if err := syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR, 1); err != nil {
  13. return err
  14. }
  15. return nil
  16. }
  17. func RetrieveOriginalDest(oob []byte) v2net.Destination {
  18. msgs, err := syscall.ParseSocketControlMessage(oob)
  19. if err != nil {
  20. return v2net.Destination{}
  21. }
  22. for _, msg := range msgs {
  23. if msg.Header.Level == syscall.SOL_IP && msg.Header.Type == syscall.IP_RECVORIGDSTADDR {
  24. ip := v2net.IPAddress(msg.Data[4:8])
  25. port := v2net.PortFromBytes(msg.Data[2:4])
  26. return v2net.UDPDestination(ip, port)
  27. } else if msg.Header.Level == syscall.SOL_IPV6 && msg.Header.Type == syscall.IP_RECVORIGDSTADDR {
  28. ip := v2net.IPAddress(msg.Data[8:24])
  29. port := v2net.PortFromBytes(msg.Data[2:4])
  30. return v2net.UDPDestination(ip, port)
  31. }
  32. }
  33. return v2net.Destination{}
  34. }
  35. func ReadUDPMsg(conn *net.UDPConn, payload []byte, oob []byte) (int, int, int, *net.UDPAddr, error) {
  36. return conn.ReadMsgUDP(payload, oob)
  37. }