2021-11-30 10:27:33 +00:00
|
|
|
package ingress
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
2024-10-31 21:05:15 +00:00
|
|
|
"net/netip"
|
2021-11-30 10:27:33 +00:00
|
|
|
)
|
|
|
|
|
2022-05-30 12:38:15 +00:00
|
|
|
type UDPProxy interface {
|
2021-11-30 10:27:33 +00:00
|
|
|
io.ReadWriteCloser
|
2022-05-30 12:38:15 +00:00
|
|
|
LocalAddr() net.Addr
|
2021-11-30 10:27:33 +00:00
|
|
|
}
|
|
|
|
|
2022-05-30 12:38:15 +00:00
|
|
|
type udpProxy struct {
|
|
|
|
*net.UDPConn
|
|
|
|
}
|
|
|
|
|
|
|
|
func DialUDP(dstIP net.IP, dstPort uint16) (UDPProxy, error) {
|
2021-11-30 10:27:33 +00:00
|
|
|
dstAddr := &net.UDPAddr{
|
|
|
|
IP: dstIP,
|
|
|
|
Port: int(dstPort),
|
|
|
|
}
|
|
|
|
|
|
|
|
// We use nil as local addr to force runtime to find the best suitable local address IP given the destination
|
|
|
|
// address as context.
|
|
|
|
udpConn, err := net.DialUDP("udp", nil, dstAddr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to create UDP proxy to origin (%v:%v): %w", dstIP, dstPort, err)
|
|
|
|
}
|
|
|
|
|
2022-05-30 12:38:15 +00:00
|
|
|
return &udpProxy{udpConn}, nil
|
2021-11-30 10:27:33 +00:00
|
|
|
}
|
2024-10-31 21:05:15 +00:00
|
|
|
|
|
|
|
func DialUDPAddrPort(dest netip.AddrPort) (*net.UDPConn, error) {
|
|
|
|
addr := net.UDPAddrFromAddrPort(dest)
|
|
|
|
|
|
|
|
// We use nil as local addr to force runtime to find the best suitable local address IP given the destination
|
|
|
|
// address as context.
|
|
|
|
udpConn, err := net.DialUDP("udp", nil, addr)
|
|
|
|
if err != nil {
|
2024-11-12 18:54:37 +00:00
|
|
|
return nil, fmt.Errorf("unable to dial udp to origin %s: %w", dest, err)
|
2024-10-31 21:05:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return udpConn, nil
|
|
|
|
}
|