...
1 package netns
2
3 import (
4 "fmt"
5
6 "golang.org/x/sys/unix"
7 )
8
9
10
11 type NsHandle int
12
13
14
15
16 func (ns NsHandle) Equal(other NsHandle) bool {
17 if ns == other {
18 return true
19 }
20 var s1, s2 unix.Stat_t
21 if err := unix.Fstat(int(ns), &s1); err != nil {
22 return false
23 }
24 if err := unix.Fstat(int(other), &s2); err != nil {
25 return false
26 }
27 return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
28 }
29
30
31 func (ns NsHandle) String() string {
32 if ns == -1 {
33 return "NS(none)"
34 }
35 var s unix.Stat_t
36 if err := unix.Fstat(int(ns), &s); err != nil {
37 return fmt.Sprintf("NS(%d: unknown)", ns)
38 }
39 return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino)
40 }
41
42
43
44 func (ns NsHandle) UniqueId() string {
45 if ns == -1 {
46 return "NS(none)"
47 }
48 var s unix.Stat_t
49 if err := unix.Fstat(int(ns), &s); err != nil {
50 return "NS(unknown)"
51 }
52 return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino)
53 }
54
55
56 func (ns NsHandle) IsOpen() bool {
57 return ns != -1
58 }
59
60
61
62 func (ns *NsHandle) Close() error {
63 if err := unix.Close(int(*ns)); err != nil {
64 return err
65 }
66 *ns = -1
67 return nil
68 }
69
70
71 func None() NsHandle {
72 return NsHandle(-1)
73 }
74
View as plain text