port.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // Bytes returns the correspoding bytes of a Port, in big endian order.
  35. func (p Port) Bytes(b []byte) []byte {
  36. return serial.Uint16ToBytes(p.Value(), b)
  37. }
  38. // String returns the string presentation of a Port.
  39. func (p Port) String() string {
  40. return serial.Uint16ToString(p.Value())
  41. }
  42. // FromPort returns the begining port of this PortRange.
  43. func (p PortRange) FromPort() Port {
  44. return Port(p.From)
  45. }
  46. // ToPort returns the end port of this PortRange.
  47. func (p PortRange) ToPort() Port {
  48. return Port(p.To)
  49. }
  50. // Contains returns true if the given port is within the range of a PortRange.
  51. func (p PortRange) Contains(port Port) bool {
  52. return p.FromPort() <= port && port <= p.ToPort()
  53. }
  54. // SinglePortRange returns a PortRange contains a single port.
  55. func SinglePortRange(p Port) *PortRange {
  56. return &PortRange{
  57. From: uint32(p),
  58. To: uint32(p),
  59. }
  60. }