port.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package net
  2. import (
  3. "encoding/binary"
  4. "strconv"
  5. "v2ray.com/core/common/serial"
  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), newError("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), newError("invalid port range: ", s)
  28. }
  29. return PortFromInt(uint32(val))
  30. }
  31. // Value return the correspoding 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 serial.Uint16ToString(p.Value())
  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. }