From 6476a2b64a2e1ea6c0d695127d726a348cc5c99b Mon Sep 17 00:00:00 2001 From: Ondrej Fabry Date: Thu, 31 Jan 2019 08:23:02 +0100 Subject: Generator improvements - all objects are now sorted alphabetically for more consistent output - unions now have constructor generated - log level for warnings was changed to debug - GetAllMessages renamed to GetRegisteredMessages Change-Id: I976453004a2fd8b6cb95ca0acfcef56913bf8d38 Signed-off-by: Ondrej Fabry --- examples/cmd/union-example/union_example.go | 42 ++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) (limited to 'examples/cmd/union-example/union_example.go') diff --git a/examples/cmd/union-example/union_example.go b/examples/cmd/union-example/union_example.go index 0f801d2..d4563c6 100644 --- a/examples/cmd/union-example/union_example.go +++ b/examples/cmd/union-example/union_example.go @@ -17,13 +17,20 @@ package main import ( "bytes" + "fmt" "log" + "net" "git.fd.io/govpp.git/examples/bin_api/ip" "github.com/lunixbochs/struc" ) func main() { + encodingExample() + usageExample() +} + +func encodingExample() { // create union with IPv4 address var unionIP4 ip.AddressUnion unionIP4.SetIP4(ip.IP4Address{192, 168, 1, 10}) @@ -31,7 +38,7 @@ func main() { // use it in the Address type addr := &ip.Address{ Af: ip.ADDRESS_IP4, - Un: unionIP4, + Un: ip.AddressUnionIP4(ip.IP4Address{192, 168, 1, 10}), } log.Printf("encoding union IPv4: %v", addr.Un.GetIP4()) @@ -61,3 +68,36 @@ func decode(data []byte) *ip.Address { log.Printf("decoded address: %#v", addr) return addr } + +func usageExample() { + var convAddr = func(ip string) { + addr, err := ipToAddress(ip) + if err != nil { + log.Printf("converting ip %q failed: %v", ip, err) + } + fmt.Printf("% 0X\n", addr) + } + + convAddr("10.10.10.10") + convAddr("::1") + convAddr("") +} + +func ipToAddress(ipstr string) (addr ip.Address, err error) { + netIP := net.ParseIP(ipstr) + if netIP == nil { + return ip.Address{}, fmt.Errorf("invalid IP: %q", ipstr) + } + if ip4 := netIP.To4(); ip4 == nil { + addr.Af = ip.ADDRESS_IP6 + var ip6addr ip.IP6Address + copy(ip6addr[:], netIP.To16()) + addr.Un.SetIP6(ip6addr) + } else { + addr.Af = ip.ADDRESS_IP4 + var ip4addr ip.IP4Address + copy(ip4addr[:], ip4) + addr.Un.SetIP4(ip4addr) + } + return +} -- cgit 1.2.3-korg