origin_udp_proxy.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package ingress
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "net/netip"
  7. )
  8. type UDPProxy interface {
  9. io.ReadWriteCloser
  10. LocalAddr() net.Addr
  11. }
  12. type udpProxy struct {
  13. *net.UDPConn
  14. }
  15. func DialUDP(dstIP net.IP, dstPort uint16) (UDPProxy, error) {
  16. dstAddr := &net.UDPAddr{
  17. IP: dstIP,
  18. Port: int(dstPort),
  19. }
  20. // We use nil as local addr to force runtime to find the best suitable local address IP given the destination
  21. // address as context.
  22. udpConn, err := net.DialUDP("udp", nil, dstAddr)
  23. if err != nil {
  24. return nil, fmt.Errorf("unable to create UDP proxy to origin (%v:%v): %w", dstIP, dstPort, err)
  25. }
  26. return &udpProxy{udpConn}, nil
  27. }
  28. func DialUDPAddrPort(dest netip.AddrPort) (*net.UDPConn, error) {
  29. addr := net.UDPAddrFromAddrPort(dest)
  30. // We use nil as local addr to force runtime to find the best suitable local address IP given the destination
  31. // address as context.
  32. udpConn, err := net.DialUDP("udp", nil, addr)
  33. if err != nil {
  34. return nil, fmt.Errorf("unable to dial udp to origin %s: %w", dest, err)
  35. }
  36. return udpConn, nil
  37. }