port.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package net
  2. import (
  3. "encoding/binary"
  4. "strconv"
  5. "github.com/xtls/xray-core/common/errors"
  6. )
  7. // Port represents a network port in TCP and UDP protocol.
  8. type Port uint16
  9. // PortFromBytes converts a byte array to a Port, assuming bytes are in big endian order.
  10. // @unsafe Caller must ensure that the byte array has at least 2 elements.
  11. func PortFromBytes(port []byte) Port {
  12. return Port(binary.BigEndian.Uint16(port))
  13. }
  14. // PortFromInt converts an integer to a Port.
  15. // @error when the integer is not positive or larger then 65535
  16. func PortFromInt(val uint32) (Port, error) {
  17. if val > 65535 {
  18. return Port(0), errors.New("invalid port range: ", val)
  19. }
  20. return Port(val), nil
  21. }
  22. // PortFromString converts a string to a Port.
  23. // @error when the string is not an integer or the integral value is a not a valid Port.
  24. func PortFromString(s string) (Port, error) {
  25. val, err := strconv.ParseUint(s, 10, 32)
  26. if err != nil {
  27. return Port(0), errors.New("invalid port range: ", s)
  28. }
  29. return PortFromInt(uint32(val))
  30. }
  31. // Value return the corresponding uint16 value of a Port.
  32. func (p Port) Value() uint16 {
  33. return uint16(p)
  34. }
  35. // String returns the string presentation of a Port.
  36. func (p Port) String() string {
  37. return strconv.Itoa(int(p))
  38. }
  39. // FromPort returns the beginning port of this PortRange.
  40. func (p *PortRange) FromPort() Port {
  41. return Port(p.From)
  42. }
  43. // ToPort returns the end port of this PortRange.
  44. func (p *PortRange) ToPort() Port {
  45. return Port(p.To)
  46. }
  47. // Contains returns true if the given port is within the range of a PortRange.
  48. func (p *PortRange) Contains(port Port) bool {
  49. return p.FromPort() <= port && port <= p.ToPort()
  50. }
  51. // SinglePortRange returns a PortRange contains a single port.
  52. func SinglePortRange(p Port) *PortRange {
  53. return &PortRange{
  54. From: uint32(p),
  55. To: uint32(p),
  56. }
  57. }
  58. type MemoryPortRange struct {
  59. From Port
  60. To Port
  61. }
  62. func (r MemoryPortRange) Contains(port Port) bool {
  63. return r.From <= port && port <= r.To
  64. }
  65. type MemoryPortList []MemoryPortRange
  66. func PortListFromProto(l *PortList) MemoryPortList {
  67. mpl := make(MemoryPortList, 0, len(l.Range))
  68. for _, r := range l.Range {
  69. mpl = append(mpl, MemoryPortRange{From: Port(r.From), To: Port(r.To)})
  70. }
  71. return mpl
  72. }
  73. func (mpl MemoryPortList) Contains(port Port) bool {
  74. for _, pr := range mpl {
  75. if pr.Contains(port) {
  76. return true
  77. }
  78. }
  79. return false
  80. }