Skip to content

Commit

Permalink
feat: add method to return name of ns
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan1993spb committed May 2, 2023
1 parent 16c2fa0 commit 2a8a17d
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
38 changes: 38 additions & 0 deletions nshandle_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package netns

import (
"fmt"
"os"
"path/filepath"

"golang.org/x/sys/unix"
)
Expand All @@ -27,6 +29,42 @@ func (ns NsHandle) Equal(other NsHandle) bool {
return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
}

// Name returns the name of the network namespace associated with the
// handle.
func (ns NsHandle) Name() (string, error) {
if ns == -1 {
return "", nil
}

var target unix.Stat_t
if err := unix.Fstat(int(ns), &target); err != nil {
return "", err
}

// Loop through all the named network namespaces to find the target
entries, err := os.ReadDir(bindMountPath)
if err != nil {
return "", err
}

for _, entry := range entries {
name := entry.Name()
path := filepath.Join(bindMountPath, name)

var stat unix.Stat_t
if err := unix.Stat(path, &stat); err != nil {
continue
}

if stat.Dev == target.Dev && stat.Ino == target.Ino {
return name, nil
}
}

// The target ns doesn't have a name
return "", nil
}

// String shows the file descriptor number and its dev and inode.
func (ns NsHandle) String() string {
if ns == -1 {
Expand Down
31 changes: 31 additions & 0 deletions nshandle_linux_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package netns_test

import (
"testing"

"github.com/vishvananda/netns"
)

func TestNsHandle_Name(t *testing.T) {
const expectedName = "some-ns-no-one-will-ever-use"

// Create a new network namespace
ns, err := netns.NewNamed(expectedName)
if err != nil {
t.Fatalf("Failed to create network namespace: %v", err)
}

t.Cleanup(func() {
ns.Close()
netns.DeleteNamed(expectedName)
})

// Get the name of the network namespace
name, err := ns.Name()
if err != nil {
t.Fatalf("Failed to get network namespace name: %v", err)
}
if name != expectedName {
t.Fatalf("Expected name %q, got %q", expectedName, name)
}
}
6 changes: 6 additions & 0 deletions nshandle_others.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ func (ns NsHandle) Equal(_ NsHandle) bool {
return false
}

// Name returns the name of the network namespace associated with the
// handle. It is only implemented on Linux.
func (ns NsHandle) Name() string {
return ""
}

// String shows the file descriptor number and its dev and inode.
// It is only implemented on Linux, and returns "NS(none)" on other
// platforms.
Expand Down

0 comments on commit 2a8a17d

Please sign in to comment.