You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/net/port.go

68 lines
1.7 KiB

package net
import (
"errors"
"strconv"
9 years ago
"github.com/v2ray/v2ray-core/common/serial"
)
var (
// ErrInvalidPortRage indicates an error during port range parsing.
ErrInvalidPortRange = errors.New("Invalid port range.")
)
9 years ago
// Port represents a network port in TCP and UDP protocol.
9 years ago
type Port uint16
9 years ago
// PortFromBytes converts a byte array to a Port, assuming bytes are in big endian order.
// @unsafe Caller must ensure that the byte array has at least 2 elements.
func PortFromBytes(port []byte) Port {
return Port(serial.BytesToUint16(port))
}
9 years ago
// PortFromInt converts an integer to a Port.
// @error when the integer is not positive or larger then 65535
func PortFromInt(v int) (Port, error) {
if v <= 0 || v > 65535 {
return Port(0), ErrInvalidPortRange
}
return Port(v), nil
}
9 years ago
// PortFromString converts a string to a Port.
// @error when the string is not an integer or the integral value is a not a valid Port.
func PortFromString(s string) (Port, error) {
v, err := strconv.Atoi(s)
if err != nil {
return Port(0), ErrInvalidPortRange
}
return PortFromInt(v)
}
9 years ago
// Value return the correspoding uint16 value of this Port.
func (this Port) Value() uint16 {
return uint16(this)
}
9 years ago
// Bytes returns the correspoding bytes of this Port, in big endian order.
func (this Port) Bytes(b []byte) []byte {
return serial.Uint16ToBytes(this.Value(), b)
}
9 years ago
// String returns the string presentation of this Port.
func (this Port) String() string {
9 years ago
return serial.Uint16ToString(this.Value())
}
9 years ago
// PortRange represents a range of ports.
type PortRange struct {
From Port
To Port
}
9 years ago
// Contains returns true if the given port is within the range of this PortRange.
func (this PortRange) Contains(port Port) bool {
return this.From <= port && port <= this.To
}