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 "git.fd.io/govpp.git/examples/binapi/ip_types"
27 "github.com/lunixbochs/struc"
35 func encodingExample() {
36 // create union with IPv4 address
37 var unionIP4 ip.AddressUnion
38 unionIP4.SetIP4(ip.IP4Address{192, 168, 1, 10})
40 // use it in the Address type
42 Af: ip_types.ADDRESS_IP4,
43 Un: ip_types.AddressUnionIP4(ip.IP4Address{192, 168, 1, 10}),
45 log.Printf("encoding union IPv4: %v", addr.Un.GetIP4())
47 // encode the address with union
49 // decode the address with union
52 log.Printf("decoded union IPv4: %v", addr2.Un.GetIP4())
55 func encode(addr *ip.Address) []byte {
56 log.Printf("encoding address: %#v", addr)
57 buf := new(bytes.Buffer)
58 if err := struc.Pack(buf, addr); err != nil {
64 func decode(data []byte) *ip.Address {
65 addr := new(ip.Address)
66 buf := bytes.NewReader(data)
67 if err := struc.Unpack(buf, addr); err != nil {
70 log.Printf("decoded address: %#v", addr)
75 var convAddr = func(ip string) {
76 addr, err := ipToAddress(ip)
78 log.Printf("converting ip %q failed: %v", ip, err)
80 fmt.Printf("% 0X\n", addr)
83 convAddr("10.10.10.10")
88 func ipToAddress(ipstr string) (addr ip.Address, err error) {
89 netIP := net.ParseIP(ipstr)
91 return ip.Address{}, fmt.Errorf("invalid IP: %q", ipstr)
93 if ip4 := netIP.To4(); ip4 == nil {
94 addr.Af = ip_types.ADDRESS_IP6
95 var ip6addr ip.IP6Address
96 copy(ip6addr[:], netIP.To16())
97 addr.Un.SetIP6(ip6addr)
99 addr.Af = ip_types.ADDRESS_IP4
100 var ip4addr ip.IP4Address
101 copy(ip4addr[:], ip4)
102 addr.Un.SetIP4(ip4addr)