port.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package net
  2. import (
  3. "errors"
  4. "strconv"
  5. "github.com/v2ray/v2ray-core/common/serial"
  6. )
  7. var (
  8. // ErrInvalidPortRage indicates an error during port range parsing.
  9. ErrInvalidPortRange = errors.New("Invalid port range.")
  10. )
  11. // Port represents a network port in TCP and UDP protocol.
  12. type Port uint16
  13. // PortFromBytes converts a byte array to a Port, assuming bytes are in big endian order.
  14. // @unsafe Caller must ensure that the byte array has at least 2 elements.
  15. func PortFromBytes(port []byte) Port {
  16. return Port(serial.BytesToUint16(port))
  17. }
  18. // PortFromInt converts an integer to a Port.
  19. // @error when the integer is not positive or larger then 65535
  20. func PortFromInt(v int) (Port, error) {
  21. if v <= 0 || v > 65535 {
  22. return Port(0), ErrInvalidPortRange
  23. }
  24. return Port(v), nil
  25. }
  26. // PortFromString converts a string to a Port.
  27. // @error when the string is not an integer or the integral value is a not a valid Port.
  28. func PortFromString(s string) (Port, error) {
  29. v, err := strconv.Atoi(s)
  30. if err != nil {
  31. return Port(0), ErrInvalidPortRange
  32. }
  33. return PortFromInt(v)
  34. }
  35. // Value return the correspoding uint16 value of this Port.
  36. func (this Port) Value() uint16 {
  37. return uint16(this)
  38. }
  39. // Bytes returns the correspoding bytes of this Port, in big endian order.
  40. func (this Port) Bytes(b []byte) []byte {
  41. return serial.Uint16ToBytes(this.Value(), b)
  42. }
  43. // String returns the string presentation of this Port.
  44. func (this Port) String() string {
  45. return serial.Uint16ToString(this.Value())
  46. }
  47. // PortRange represents a range of ports.
  48. type PortRange struct {
  49. From Port
  50. To Port
  51. }
  52. // Contains returns true if the given port is within the range of this PortRange.
  53. func (this PortRange) Contains(port Port) bool {
  54. return this.From <= port && port <= this.To
  55. }