port.go 1.8 KB

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