addr_proto.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package proxyproto
  2. // AddressFamilyAndProtocol represents address family and transport protocol.
  3. type AddressFamilyAndProtocol byte
  4. const (
  5. UNSPEC = '\x00'
  6. TCPv4 = '\x11'
  7. UDPv4 = '\x12'
  8. TCPv6 = '\x21'
  9. UDPv6 = '\x22'
  10. UnixStream = '\x31'
  11. UnixDatagram = '\x32'
  12. )
  13. var supportedTransportProtocol = map[AddressFamilyAndProtocol]bool{
  14. TCPv4: true,
  15. UDPv4: true,
  16. TCPv6: true,
  17. UDPv6: true,
  18. UnixStream: true,
  19. UnixDatagram: true,
  20. }
  21. // IsIPv4 returns true if the address family is IPv4 (AF_INET4), false otherwise.
  22. func (ap AddressFamilyAndProtocol) IsIPv4() bool {
  23. return 0x10 == ap&0xF0
  24. }
  25. // IsIPv6 returns true if the address family is IPv6 (AF_INET6), false otherwise.
  26. func (ap AddressFamilyAndProtocol) IsIPv6() bool {
  27. return 0x20 == ap&0xF0
  28. }
  29. // IsUnix returns true if the address family is UNIX (AF_UNIX), false otherwise.
  30. func (ap AddressFamilyAndProtocol) IsUnix() bool {
  31. return 0x30 == ap&0xF0
  32. }
  33. // IsStream returns true if the transport protocol is TCP or STREAM (SOCK_STREAM), false otherwise.
  34. func (ap AddressFamilyAndProtocol) IsStream() bool {
  35. return 0x01 == ap&0x0F
  36. }
  37. // IsDatagram returns true if the transport protocol is UDP or DGRAM (SOCK_DGRAM), false otherwise.
  38. func (ap AddressFamilyAndProtocol) IsDatagram() bool {
  39. return 0x02 == ap&0x0F
  40. }
  41. // IsUnspec returns true if the transport protocol or address family is unspecified, false otherwise.
  42. func (ap AddressFamilyAndProtocol) IsUnspec() bool {
  43. return (0x00 == ap&0xF0) || (0x00 == ap&0x0F)
  44. }
  45. func (ap AddressFamilyAndProtocol) toByte() byte {
  46. if ap.IsIPv4() && ap.IsStream() {
  47. return TCPv4
  48. } else if ap.IsIPv4() && ap.IsDatagram() {
  49. return UDPv4
  50. } else if ap.IsIPv6() && ap.IsStream() {
  51. return TCPv6
  52. } else if ap.IsIPv6() && ap.IsDatagram() {
  53. return UDPv6
  54. } else if ap.IsUnix() && ap.IsStream() {
  55. return UnixStream
  56. } else if ap.IsUnix() && ap.IsDatagram() {
  57. return UnixDatagram
  58. }
  59. return UNSPEC
  60. }