Skip to content

Instantly share code, notes, and snippets.

@CMGS
Created May 18, 2015 02:14
Show Gist options
  • Save CMGS/d94bb1f761d70ccc5781 to your computer and use it in GitHub Desktop.
Save CMGS/d94bb1f761d70ccc5781 to your computer and use it in GitHub Desktop.
各种测试
package main
import (
"fmt"
"net"
"os"
"runtime"
"github.com/docker/libcontainer/netlink"
)
func minit(name string) {
netlink.NetworkLinkAddMacVlan("em1", name, "bridge")
ifc, _ := net.InterfaceByName(name)
fmt.Println("ifc in host", ifc)
netlink.NetworkSetNsPid(ifc, 19474)
}
func set(name string, p int) {
ifc, _ := net.InterfaceByName(name)
ip, ipn, _ := net.ParseCIDR(fmt.Sprintf("10.222.7.%d/16", p))
fmt.Println("set ip", ifc, netlink.NetworkLinkAddIp(ifc, ip, ipn))
fmt.Println("up link", ifc, netlink.NetworkLinkUp(ifc))
}
//func add(name string, p int) {
// runtime.LockOSThread()
// defer runtime.UnlockOSThread()
//
// origns, _ := netns.Get()
// defer origns.Close()
//
// ns, _ := netns.GetFromPid(19474)
// defer ns.Close()
//
// // Do something with tne network namespace
// ifaces, _ := net.Interfaces()
// fmt.Printf("Interfaces: %v\n", ifaces)
//
// netns.Set(origns)
//}
//
//func mai1n() {
// add("mt2", 101)
// ifc, _ := net.InterfaceByName("mt2")
// fmt.Println("check outside", ifc)
// //add("mt3", 102)
// //add("mt4", 103)
//}
//func t2() {
// // 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.GetFromPid(19474)
// defer newns.Close()
//
// // Do something with tne network namespace
// ifaces, _ := net.Interfaces()
// fmt.Printf("Interfaces: %v\n", ifaces)
//
// // Switch back to the original namespace
// netns.Set(origns)
//}
func t3() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ns, _ := netns.Setns("19474")
ifaces, _ := net.Interfaces()
fmt.Printf("Interfaces: %v\n", ifaces)
fmt.Println(ns.Close())
ns, _ = netns.Setns(string(os.Getpid()))
}
func main() {
t3()
ifaces, _ := net.Interfaces()
fmt.Printf("Interfaces: %v\n", ifaces)
}
package main
import (
"fmt"
"net"
"github.com/milosgajdos83/tenus"
)
func do(pid int, ip string, n string) {
macVlanDocker, err := tenus.NewMacVlanLinkWithOptions("em1", tenus.MacVlanOptions{Mode: "bridge", Dev: n})
fmt.Println(err)
macVlanDocker.SetLinkNetNsPid(pid)
macVlanDckrIp, macVlanDckrIpNet, _ := net.ParseCIDR(ip)
macVlanDocker.SetLinkNetInNs(pid, macVlanDckrIp, macVlanDckrIpNet, nil)
}
func main() {
fmt.Println("1")
do(19474, "10.0.41.3/16", "mt2")
fmt.Println("2")
do(43292, "10.0.41.4/16", "mt3")
fmt.Println("3")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment