port.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package net
  2. import (
  3. "strconv"
  4. "v2ray.com/core/common/errors"
  5. "v2ray.com/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(val uint32) (Port, error) {
  21. if val > 65535 {
  22. return Port(0), ErrInvalidPortRange
  23. }
  24. return Port(val), 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. val, err := strconv.ParseUint(s, 10, 32)
  30. if err != nil {
  31. return Port(0), ErrInvalidPortRange
  32. }
  33. return PortFromInt(uint32(val))
  34. }
  35. // Value return the correspoding uint16 value of v Port.
  36. func (v Port) Value() uint16 {
  37. return uint16(v)
  38. }
  39. // Bytes returns the correspoding bytes of v Port, in big endian order.
  40. func (v Port) Bytes(b []byte) []byte {
  41. return serial.Uint16ToBytes(v.Value(), b)
  42. }
  43. // String returns the string presentation of v Port.
  44. func (v Port) String() string {
  45. return serial.Uint16ToString(v.Value())
  46. }
  47. func (v PortRange) FromPort() Port {
  48. return Port(v.From)
  49. }
  50. func (v PortRange) ToPort() Port {
  51. return Port(v.To)
  52. }
  53. // Contains returns true if the given port is within the range of v PortRange.
  54. func (v PortRange) Contains(port Port) bool {
  55. return v.FromPort() <= port && port <= v.ToPort()
  56. }