diff options
author | Rastislav Szabo <raszabo@cisco.com> | 2019-01-31 07:28:52 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@fd.io> | 2019-01-31 07:28:52 +0000 |
commit | eb571ee5c0cf5a5194d6ae9aaa0be6e24ea2a943 (patch) | |
tree | 2743ea4285fe8dd9ffbc243b76441e8ca695c0e2 /examples/cmd/union-example/union_example.go | |
parent | f1f9fe44d54eec75f6484d0b91769204b6812fb5 (diff) | |
parent | 6476a2b64a2e1ea6c0d695127d726a348cc5c99b (diff) |
Merge "Generator improvements"
Diffstat (limited to 'examples/cmd/union-example/union_example.go')
-rw-r--r-- | examples/cmd/union-example/union_example.go | 42 |
1 files changed, 41 insertions, 1 deletions
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 +} |