iface.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2019 Yunion
  2. //
  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
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  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.
  14. package netutils2
  15. import (
  16. "net"
  17. "time"
  18. "yunion.io/x/pkg/errors"
  19. )
  20. func getIfaceIPs(iface *net.Interface) ([]net.IP, error) {
  21. addrs, err := iface.Addrs()
  22. if err != nil {
  23. return nil, errors.Wrap(err, "iface.Addrs")
  24. }
  25. ips := make([]net.IP, 0)
  26. for _, a := range addrs {
  27. if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  28. if ipnet.IP.To4() != nil {
  29. ips = append(ips, ipnet.IP)
  30. } else if ipnet.IP.To16() != nil {
  31. ips = append(ips, ipnet.IP)
  32. }
  33. }
  34. }
  35. return ips, nil
  36. }
  37. func WaitIfaceIps(ifname string) (*net.Interface, []net.IP, error) {
  38. iface, err := net.InterfaceByName(ifname)
  39. if err != nil {
  40. return nil, nil, errors.Wrapf(err, "net.InterfaceByName %s", ifname)
  41. }
  42. var ips []net.IP
  43. MAX := 60
  44. wait := 0
  45. for wait < MAX {
  46. ips, err = getIfaceIPs(iface)
  47. if err != nil {
  48. return nil, nil, errors.Wrap(err, "getIfaceIPs")
  49. }
  50. if len(ips) == 0 {
  51. time.Sleep(2 * time.Second)
  52. wait += 2
  53. } else {
  54. break
  55. }
  56. }
  57. return iface, ips, nil
  58. }