2 Copyright 2015 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
25 // PortRange represents a range of TCP/UDP ports. To represent a single port,
27 type PortRange struct {
32 // Contains tests whether a given port falls within the PortRange.
33 func (pr *PortRange) Contains(p int) bool {
34 return (p >= pr.Base) && ((p - pr.Base) < pr.Size)
37 // String converts the PortRange to a string representation, which can be
38 // parsed by PortRange.Set or ParsePortRange.
39 func (pr PortRange) String() string {
43 return fmt.Sprintf("%d-%d", pr.Base, pr.Base+pr.Size-1)
46 // Set parses a string of the form "value", "min-max", or "min+offset", inclusive at both ends, and
47 // sets the PortRange from it. This is part of the flag.Value and pflag.Value
49 func (pr *PortRange) Set(value string) error {
51 SinglePortNotation = 1 << iota
56 value = strings.TrimSpace(value)
57 hyphenIndex := strings.Index(value, "-")
58 plusIndex := strings.Index(value, "+")
70 if plusIndex == -1 && hyphenIndex == -1 {
71 notation |= SinglePortNotation
73 if hyphenIndex != -1 {
74 notation |= HyphenNotation
77 notation |= PlusNotation
81 case SinglePortNotation:
83 port, err = strconv.Atoi(value)
90 low, err = strconv.Atoi(value[:hyphenIndex])
94 high, err = strconv.Atoi(value[hyphenIndex+1:])
100 low, err = strconv.Atoi(value[:plusIndex])
104 offset, err = strconv.Atoi(value[plusIndex+1:])
110 return fmt.Errorf("unable to parse port range: %s", value)
113 if low > 65535 || high > 65535 {
114 return fmt.Errorf("the port range cannot be greater than 65535: %s", value)
118 return fmt.Errorf("end port cannot be less than start port: %s", value)
122 pr.Size = 1 + high - low
126 // Type returns a descriptive string about this type. This is part of the
127 // pflag.Value interface.
128 func (*PortRange) Type() string {
132 // ParsePortRange parses a string of the form "min-max", inclusive at both
133 // ends, and initializs a new PortRange from it.
134 func ParsePortRange(value string) (*PortRange, error) {
143 func ParsePortRangeOrDie(value string) *PortRange {
144 pr, err := ParsePortRange(value)
146 panic(fmt.Sprintf("couldn't parse port range %q: %v", value, err))