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/codec"
25 "git.fd.io/govpp.git/examples/binapi/ip"
26 "git.fd.io/govpp.git/examples/binapi/ip_types"
38 // convert IP from string form into Address type containing union
39 convertIP("10.10.1.1")
43 func constructExample() {
44 var union ip_types.AddressUnion
46 // create AddressUnion with AdressUnionXXX constructors
47 union = ip_types.AddressUnionIP4(ip.IP4Address{192, 168, 1, 10})
48 union = ip_types.AddressUnionIP6(ip.IP6Address{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02})
50 // set AddressUnion with SetXXX methods
51 union.SetIP4(ip.IP4Address{192, 168, 1, 10})
52 union.SetIP6(ip.IP6Address{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02})
55 func encodingExample() {
58 // encode this message
59 var msg = ip.IPPuntRedirect{
60 Punt: ip.PuntRedirect{
62 Af: ip_types.ADDRESS_IP4,
63 Un: ip_types.AddressUnionIP4(ip.IP4Address{192, 168, 1, 10}),
68 log.Printf("encoding message: %+v", msg)
70 b, err := c.EncodeMsg(&msg, 1)
75 // decode into this message
76 var msg2 ip.IPPuntRedirect
77 if err := c.DecodeMsg(b, &msg2); err != nil {
80 log.Printf("decoded message: %+v", msg2)
82 // compare the messages
83 if !reflect.DeepEqual(msg, msg2) {
84 log.Fatal("messages are not equal")
88 func convertIP(ip string) {
89 addr, err := ipToAddress(ip)
91 log.Printf("error converting IP: %v", err)
94 fmt.Printf("converted IP %q to: %+v\n", ip, addr)
97 func ipToAddress(ipstr string) (addr ip.Address, err error) {
98 netIP := net.ParseIP(ipstr)
100 return ip.Address{}, fmt.Errorf("invalid IP: %q", ipstr)
102 if ip4 := netIP.To4(); ip4 == nil {
103 addr.Af = ip_types.ADDRESS_IP6
104 var ip6addr ip.IP6Address
105 copy(ip6addr[:], netIP.To16())
106 addr.Un.SetIP6(ip6addr)
108 addr.Af = ip_types.ADDRESS_IP4
109 var ip4addr ip.IP4Address
110 copy(ip4addr[:], ip4.To4())
111 addr.Un.SetIP4(ip4addr)