github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/iputil/ipnet.go (about) 1 package iputil 2 3 import ( 4 "encoding/json" 5 "net" 6 "strings" 7 8 "sigs.k8s.io/kustomize/kyaml/yaml" 9 10 "github.com/telepresenceio/telepresence/rpc/v2/manager" 11 ) 12 13 func ConvertSubnets(ms []*manager.IPNet) []*net.IPNet { 14 ns := make([]*net.IPNet, len(ms)) 15 for i, m := range ms { 16 n := IPNetFromRPC(m) 17 ns[i] = n 18 } 19 return ns 20 } 21 22 func IPNetToRPC(n *net.IPNet) *manager.IPNet { 23 ones, _ := n.Mask.Size() 24 return &manager.IPNet{ 25 Ip: n.IP, 26 Mask: int32(ones), 27 } 28 } 29 30 func IPNetFromRPC(r *manager.IPNet) *net.IPNet { 31 return &net.IPNet{ 32 IP: r.Ip, 33 Mask: net.CIDRMask(int(r.Mask), len(r.Ip)*8), 34 } 35 } 36 37 func IsIpV6Addr(ipAddStr string) bool { 38 return strings.Count(ipAddStr, ":") >= 2 39 } 40 41 // Subnet is a net.IPNet that can be marshalled/unmarshalled as yaml or json. 42 type Subnet net.IPNet 43 44 func (s *Subnet) MarshalJSON() ([]byte, error) { 45 return json.Marshal(s.String()) 46 } 47 48 func (s *Subnet) UnmarshalJSON(data []byte) error { 49 var str string 50 if err := json.Unmarshal(data, &str); err != nil { 51 return err 52 } 53 _, ipNet, err := net.ParseCIDR(str) 54 if err != nil { 55 return err 56 } 57 *s = *(*Subnet)(ipNet) 58 return nil 59 } 60 61 func (s *Subnet) MarshalYAML() (any, error) { 62 return s.String(), nil 63 } 64 65 func (s *Subnet) UnmarshalYAML(node *yaml.Node) error { 66 var str string 67 if err := node.Decode(&str); err != nil { 68 return err 69 } 70 _, ipNet, err := net.ParseCIDR(str) 71 if err != nil { 72 return err 73 } 74 *s = *(*Subnet)(ipNet) 75 return nil 76 } 77 78 func (s *Subnet) String() string { 79 return (*net.IPNet)(s).String() 80 }