port.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package net
  2. import (
  3. "strconv"
  4. "v2ray.com/core/common/serial"
  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(serial.BytesToUint16(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 correspoding 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 serial.Uint16ToString(p.Value())
  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. }