nettype.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package nettype defines an interface that doesn't exist in the Go net package.
  4. package nettype
  5. import (
  6. "context"
  7. "io"
  8. "net"
  9. "net/netip"
  10. "time"
  11. )
  12. // PacketListener defines the ListenPacket method as implemented
  13. // by net.ListenConfig, net.ListenPacket, and tstest/natlab.
  14. type PacketListener interface {
  15. ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error)
  16. }
  17. type PacketListenerWithNetIP interface {
  18. ListenPacket(ctx context.Context, network, address string) (PacketConn, error)
  19. }
  20. // Std implements PacketListener using the Go net package's ListenPacket func.
  21. type Std struct{}
  22. func (Std) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
  23. var conf net.ListenConfig
  24. return conf.ListenPacket(ctx, network, address)
  25. }
  26. // PacketConn is like a net.PacketConn but uses the newer netip.AddrPort
  27. // write/read methods.
  28. type PacketConn interface {
  29. WriteToUDPAddrPort([]byte, netip.AddrPort) (int, error)
  30. ReadFromUDPAddrPort([]byte) (int, netip.AddrPort, error)
  31. io.Closer
  32. LocalAddr() net.Addr
  33. SetDeadline(time.Time) error
  34. SetReadDeadline(time.Time) error
  35. SetWriteDeadline(time.Time) error
  36. }
  37. func MakePacketListenerWithNetIP(ln PacketListener) PacketListenerWithNetIP {
  38. return packetListenerAdapter{ln}
  39. }
  40. type packetListenerAdapter struct {
  41. PacketListener
  42. }
  43. func (a packetListenerAdapter) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
  44. pc, err := a.PacketListener.ListenPacket(ctx, network, address)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return pc.(PacketConn), nil
  49. }
  50. // ConnPacketConn is the interface that's a superset of net.Conn and net.PacketConn.
  51. type ConnPacketConn interface {
  52. net.Conn
  53. net.PacketConn
  54. }