1 // Copyright (c) 2018 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // union-example is an example to show how to use unions in VPP binary API.
24 "git.fd.io/govpp.git/examples/binapi/ip"
25 "github.com/lunixbochs/struc"
33 func encodingExample() {
34 // create union with IPv4 address
35 var unionIP4 ip.AddressUnion
36 unionIP4.SetIP4(ip.IP4Address{192, 168, 1, 10})
38 // use it in the Address type
41 Un: ip.AddressUnionIP4(ip.IP4Address{192, 168, 1, 10}),
43 log.Printf("encoding union IPv4: %v", addr.Un.GetIP4())
45 // encode the address with union
47 // decode the address with union
50 log.Printf("decoded union IPv4: %v", addr2.Un.GetIP4())
53 func encode(addr *ip.Address) []byte {
54 log.Printf("encoding address: %#v", addr)
55 buf := new(bytes.Buffer)
56 if err := struc.Pack(buf, addr); err != nil {
62 func decode(data []byte) *ip.Address {
63 addr := new(ip.Address)
64 buf := bytes.NewReader(data)
65 if err := struc.Unpack(buf, addr); err != nil {
68 log.Printf("decoded address: %#v", addr)
73 var convAddr = func(ip string) {
74 addr, err := ipToAddress(ip)
76 log.Printf("converting ip %q failed: %v", ip, err)
78 fmt.Printf("% 0X\n", addr)
81 convAddr("10.10.10.10")
86 func ipToAddress(ipstr string) (addr ip.Address, err error) {
87 netIP := net.ParseIP(ipstr)
89 return ip.Address{}, fmt.Errorf("invalid IP: %q", ipstr)
91 if ip4 := netIP.To4(); ip4 == nil {
92 addr.Af = ip.ADDRESS_IP6
93 var ip6addr ip.IP6Address
94 copy(ip6addr[:], netIP.To16())
95 addr.Un.SetIP6(ip6addr)
97 addr.Af = ip.ADDRESS_IP4
98 var ip4addr ip.IP4Address
100 addr.Un.SetIP4(ip4addr)