Hunter0x7c7
2022-08-11 b8230139fb40edea387617b6accd8371e37eda58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package net
 
import (
    "encoding/binary"
    "strconv"
)
 
// Port represents a network port in TCP and UDP protocol.
type Port uint16
 
// 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(binary.BigEndian.Uint16(port))
}
 
// PortFromInt converts an integer to a Port.
// @error when the integer is not positive or larger then 65535
func PortFromInt(val uint32) (Port, error) {
    if val > 65535 {
        return Port(0), newError("invalid port range: ", val)
    }
    return Port(val), nil
}
 
// 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) {
    val, err := strconv.ParseUint(s, 10, 32)
    if err != nil {
        return Port(0), newError("invalid port range: ", s)
    }
    return PortFromInt(uint32(val))
}
 
// Value return the corresponding uint16 value of a Port.
func (p Port) Value() uint16 {
    return uint16(p)
}
 
// String returns the string presentation of a Port.
func (p Port) String() string {
    return strconv.Itoa(int(p))
}
 
// FromPort returns the beginning port of this PortRange.
func (p *PortRange) FromPort() Port {
    return Port(p.From)
}
 
// ToPort returns the end port of this PortRange.
func (p *PortRange) ToPort() Port {
    return Port(p.To)
}
 
// Contains returns true if the given port is within the range of a PortRange.
func (p *PortRange) Contains(port Port) bool {
    return p.FromPort() <= port && port <= p.ToPort()
}
 
// SinglePortRange returns a PortRange contains a single port.
func SinglePortRange(p Port) *PortRange {
    return &PortRange{
        From: uint32(p),
        To:   uint32(p),
    }
}
 
type MemoryPortRange struct {
    From Port
    To   Port
}
 
func (r MemoryPortRange) Contains(port Port) bool {
    return r.From <= port && port <= r.To
}
 
type MemoryPortList []MemoryPortRange
 
func PortListFromProto(l *PortList) MemoryPortList {
    mpl := make(MemoryPortList, 0, len(l.Range))
    for _, r := range l.Range {
        mpl = append(mpl, MemoryPortRange{From: Port(r.From), To: Port(r.To)})
    }
    return mpl
}
 
func (mpl MemoryPortList) Contains(port Port) bool {
    for _, pr := range mpl {
        if pr.Contains(port) {
            return true
        }
    }
    return false
}