nettype.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright (c) Tailscale Inc & AUTHORS
  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. "net"
  8. "net/netip"
  9. )
  10. // PacketListener defines the ListenPacket method as implemented
  11. // by net.ListenConfig, net.ListenPacket, and tstest/natlab.
  12. type PacketListener interface {
  13. ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error)
  14. }
  15. type PacketListenerWithNetIP interface {
  16. ListenPacket(ctx context.Context, network, address string) (PacketConn, error)
  17. }
  18. // Std implements PacketListener using the Go net package's ListenPacket func.
  19. type Std struct{}
  20. func (Std) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
  21. var conf net.ListenConfig
  22. return conf.ListenPacket(ctx, network, address)
  23. }
  24. type PacketConn interface {
  25. net.PacketConn
  26. WriteToUDPAddrPort([]byte, netip.AddrPort) (int, error)
  27. }
  28. func MakePacketListenerWithNetIP(ln PacketListener) PacketListenerWithNetIP {
  29. return packetListenerAdapter{ln}
  30. }
  31. type packetListenerAdapter struct {
  32. PacketListener
  33. }
  34. func (a packetListenerAdapter) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
  35. pc, err := a.PacketListener.ListenPacket(ctx, network, address)
  36. if err != nil {
  37. return nil, err
  38. }
  39. return pc.(PacketConn), nil
  40. }
  41. // ConnPacketConn is the interface that's a superset of net.Conn and net.PacketConn.
  42. type ConnPacketConn interface {
  43. net.Conn
  44. net.PacketConn
  45. }