github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/libnetwork/cmd/readme_test/readme.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/docker/docker/pkg/reexec" 8 "github.com/docker/libnetwork" 9 "github.com/docker/libnetwork/config" 10 "github.com/docker/libnetwork/netlabel" 11 "github.com/docker/libnetwork/options" 12 ) 13 14 func main() { 15 if reexec.Init() { 16 return 17 } 18 19 // Select and configure the network driver 20 networkType := "bridge" 21 22 // Create a new controller instance 23 driverOptions := options.Generic{} 24 genericOption := make(map[string]interface{}) 25 genericOption[netlabel.GenericData] = driverOptions 26 controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption)) 27 if err != nil { 28 log.Fatalf("libnetwork.New: %s", err) 29 } 30 31 // Create a network for containers to join. 32 // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use. 33 network, err := controller.NewNetwork(networkType, "network1", "") 34 if err != nil { 35 log.Fatalf("controller.NewNetwork: %s", err) 36 } 37 38 // For each new container: allocate IP and interfaces. The returned network 39 // settings will be used for container infos (inspect and such), as well as 40 // iptables rules for port publishing. This info is contained or accessible 41 // from the returned endpoint. 42 ep, err := network.CreateEndpoint("Endpoint1") 43 if err != nil { 44 log.Fatalf("network.CreateEndpoint: %s", err) 45 } 46 47 // Create the sandbox for the container. 48 // NewSandbox accepts Variadic optional arguments which libnetwork can use. 49 sbx, err := controller.NewSandbox("container1", 50 libnetwork.OptionHostname("test"), 51 libnetwork.OptionDomainname("docker.io")) 52 if err != nil { 53 log.Fatalf("controller.NewSandbox: %s", err) 54 } 55 56 // A sandbox can join the endpoint via the join api. 57 err = ep.Join(sbx) 58 if err != nil { 59 log.Fatalf("ep.Join: %s", err) 60 } 61 62 // libnetwork client can check the endpoint's operational data via the Info() API 63 epInfo, err := ep.DriverInfo() 64 if err != nil { 65 log.Fatalf("ep.DriverInfo: %s", err) 66 } 67 68 macAddress, ok := epInfo[netlabel.MacAddress] 69 if !ok { 70 log.Fatal("failed to get mac address from endpoint info") 71 } 72 73 fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key()) 74 }