2017-03-06 04:17:55 -05:00
|
|
|
# netns - network namespaces in go #
|
|
|
|
|
|
|
|
The netns package provides an ultra-simple interface for handling
|
|
|
|
network namespaces in go. Changing namespaces requires elevated
|
|
|
|
privileges, so in most cases this code needs to be run as root.
|
|
|
|
|
|
|
|
## Local Build and Test ##
|
|
|
|
|
|
|
|
You can use go get command:
|
|
|
|
|
|
|
|
go get github.com/vishvananda/netns
|
|
|
|
|
|
|
|
Testing (requires root):
|
|
|
|
|
|
|
|
sudo -E go test github.com/vishvananda/netns
|
|
|
|
|
|
|
|
## Example ##
|
|
|
|
|
|
|
|
```go
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2019-04-10 13:09:53 -04:00
|
|
|
"fmt"
|
2017-03-06 04:17:55 -05:00
|
|
|
"net"
|
|
|
|
"runtime"
|
2019-04-10 13:09:53 -04:00
|
|
|
"github.com/vishvananda/netns"
|
2017-03-06 04:17:55 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// Lock the OS Thread so we don't accidentally switch namespaces
|
|
|
|
runtime.LockOSThread()
|
|
|
|
defer runtime.UnlockOSThread()
|
|
|
|
|
|
|
|
// Save the current network namespace
|
|
|
|
origns, _ := netns.Get()
|
|
|
|
defer origns.Close()
|
|
|
|
|
|
|
|
// Create a new network namespace
|
|
|
|
newns, _ := netns.New()
|
|
|
|
defer newns.Close()
|
|
|
|
|
2019-04-10 13:09:53 -04:00
|
|
|
// Do something with the network namespace
|
2017-03-06 04:17:55 -05:00
|
|
|
ifaces, _ := net.Interfaces()
|
|
|
|
fmt.Printf("Interfaces: %v\n", ifaces)
|
|
|
|
|
|
|
|
// Switch back to the original namespace
|
|
|
|
netns.Set(origns)
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
2022-03-01 16:58:47 -05:00
|
|
|
|
|
|
|
## NOTE
|
|
|
|
|
|
|
|
The library can be safely used only with Go >= 1.10 due to [golang/go#20676](https://github.com/golang/go/issues/20676).
|
|
|
|
|
|
|
|
After locking a goroutine to its current OS thread with `runtime.LockOSThread()`
|
|
|
|
and changing its network namespace, any new subsequent goroutine won't be
|
|
|
|
scheduled on that thread while it's locked. Therefore, the new goroutine
|
|
|
|
will run in a different namespace leading to unexpected results.
|
|
|
|
|
|
|
|
See [here](https://www.weave.works/blog/linux-namespaces-golang-followup) for more details.
|