port.go 2.3 KB

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