Last active
November 6, 2020 21:12
-
-
Save 0xc0d/8763ad2bd9772cc4c6879e3371d661cb to your computer and use it in GitHub Desktop.
Create new network namespace without any process member
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func MountNewNetworkNamespace(nsTarget string) (filesystem.Unmounter, error) { | |
_, err := os.OpenFile(nsTarget, syscall.O_RDONLY|syscall.O_CREAT|syscall.O_EXCL, 0644) | |
if err != nil { | |
return nil, errors.Wrap(err, "unable to create target file") | |
} | |
// store current network namespace | |
file, err = os.OpenFile("/proc/self/ns/net", os.O_RDONLY, 0) | |
if err != nil { | |
return nil, err | |
} | |
defer file.Close() | |
if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil { | |
return nil, errors.Wrap(err, "unshare syscall failed") | |
} | |
mountPoint := filesystem.MountOption{ | |
Source: "/proc/self/ns/net", | |
Target: nsTarget, | |
Type: "bind", | |
Flag: syscall.MS_BIND, | |
} | |
unmount, err := filesystem.Mount(mountPoint) | |
if err != nil { | |
return unmount, err | |
} | |
// reset previous network namespace | |
if err := unix.Setns(int(file.Fd()), syscall.CLONE_NEWNET); err != nil { | |
return unmount, errors.Wrap(err, "setns syscall failed: ") | |
} | |
return unmount, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment