port.go 1.8 KB

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