iface_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // +build !windows
  2. // Copyright 2017 flannel authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package ip
  16. import (
  17. "net"
  18. "testing"
  19. "github.com/flannel-io/flannel/pkg/ns"
  20. "github.com/vishvananda/netlink"
  21. )
  22. func TestEnsureV4AddressOnLink(t *testing.T) {
  23. teardown := ns.SetUpNetlinkTest(t)
  24. defer teardown()
  25. lo, err := netlink.LinkByName("lo")
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. if err := netlink.LinkSetUp(lo); err != nil {
  30. t.Fatal(err)
  31. }
  32. // check changing address
  33. ipn := IP4Net{IP: FromIP(net.ParseIP("127.0.0.2")), PrefixLen: 24}
  34. if err := EnsureV4AddressOnLink(ipn, ipn, lo); err != nil {
  35. t.Fatal(err)
  36. }
  37. addrs, err := netlink.AddrList(lo, netlink.FAMILY_V4)
  38. if err != nil {
  39. t.Fatal(err)
  40. }
  41. if len(addrs) != 1 || addrs[0].String() != "127.0.0.2/24 lo" {
  42. t.Fatalf("addrs %v is not expected", addrs)
  43. }
  44. // check changing address if there exist unknown addresses
  45. if err := netlink.AddrAdd(lo, &netlink.Addr{IPNet: &net.IPNet{IP: net.ParseIP("127.0.1.1"), Mask: net.CIDRMask(24, 32)}}); err != nil {
  46. t.Fatal(err)
  47. }
  48. if err := EnsureV4AddressOnLink(ipn, ipn, lo); err != nil {
  49. t.Fatal(err)
  50. }
  51. addrs, err = netlink.AddrList(lo, netlink.FAMILY_V4)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. if len(addrs) != 2 {
  56. t.Fatalf("two addresses expected, addrs: %v", addrs)
  57. }
  58. }