github.com/containerd/nerdctl@v1.7.7/pkg/containerinspector/containerinspector_linux.go (about) 1 /* 2 Copyright The containerd Authors. 3 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 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 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. 15 */ 16 17 package containerinspector 18 19 import ( 20 "context" 21 "fmt" 22 "net" 23 "strings" 24 25 "github.com/containerd/nerdctl/pkg/inspecttypes/native" 26 27 "github.com/containernetworking/plugins/pkg/ns" 28 ) 29 30 func InspectNetNS(ctx context.Context, pid int) (*native.NetNS, error) { 31 nsPath := fmt.Sprintf("/proc/%d/ns/net", pid) 32 res := &native.NetNS{} 33 fn := func(_ ns.NetNS) error { 34 intf, err := net.Interfaces() 35 if err != nil { 36 return err 37 } 38 res.Interfaces = make([]native.NetInterface, len(intf)) 39 for i, f := range intf { 40 x := native.NetInterface{ 41 Interface: f, 42 } 43 if f.HardwareAddr != nil { 44 x.HardwareAddr = f.HardwareAddr.String() 45 } 46 if x.Interface.Flags.String() != "0" { 47 x.Flags = strings.Split(x.Interface.Flags.String(), "|") 48 } 49 if addrs, err := x.Interface.Addrs(); err == nil { 50 x.Addrs = make([]string, len(addrs)) 51 for j, a := range addrs { 52 x.Addrs[j] = a.String() 53 } 54 } 55 res.Interfaces[i] = x 56 } 57 res.PrimaryInterface = determinePrimaryInterface(res.Interfaces) 58 return nil 59 } 60 if err := ns.WithNetNSPath(nsPath, fn); err != nil { 61 return nil, err 62 } 63 return res, nil 64 } 65 66 // determinePrimaryInterface returns a net.Interface.Index value, not a slice index. 67 // Zero means no primary interface was detected. 68 func determinePrimaryInterface(interfaces []native.NetInterface) int { 69 for _, f := range interfaces { 70 if f.Interface.Flags&net.FlagLoopback == 0 && f.Interface.Flags&net.FlagUp != 0 && !strings.HasPrefix(f.Name, "lo") { 71 return f.Index 72 } 73 } 74 return 0 75 }