You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.2 KiB

  1. /*
  2. * Minio Cloud Storage, (C) 2016 Minio, Inc.
  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. */
  16. package cmd
  17. import (
  18. "fmt"
  19. "net"
  20. "sort"
  21. )
  22. // byLastOctetValue implements sort.Interface used in sorting a list
  23. // of ip address by their last octet value.
  24. type byLastOctetValue []net.IP
  25. func (n byLastOctetValue) Len() int { return len(n) }
  26. func (n byLastOctetValue) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
  27. func (n byLastOctetValue) Less(i, j int) bool {
  28. return []byte(n[i].To4())[3] < []byte(n[j].To4())[3]
  29. }
  30. // getInterfaceIPv4s is synonymous to net.InterfaceAddrs()
  31. // returns net.IP IPv4 only representation of the net.Addr.
  32. // Additionally the returned list is sorted by their last
  33. // octet value.
  34. //
  35. // [The logic to sort by last octet is implemented to
  36. // prefer CIDRs with higher octects, this in-turn skips the
  37. // localhost/loopback address to be not preferred as the
  38. // first ip on the list. Subsequently this list helps us print
  39. // a user friendly message with appropriate values].
  40. func getInterfaceIPv4s() ([]net.IP, error) {
  41. addrs, err := net.InterfaceAddrs()
  42. if err != nil {
  43. return nil, fmt.Errorf("Unable to determine network interface address. %s", err)
  44. }
  45. // Go through each return network address and collate IPv4 addresses.
  46. var nips []net.IP
  47. for _, addr := range addrs {
  48. if addr.Network() == "ip+net" {
  49. var nip net.IP
  50. // Attempt to parse the addr through CIDR.
  51. nip, _, err = net.ParseCIDR(addr.String())
  52. if err != nil {
  53. return nil, fmt.Errorf("Unable to parse addrss %s, error %s", addr, err)
  54. }
  55. // Collect only IPv4 addrs.
  56. if nip.To4() != nil {
  57. nips = append(nips, nip)
  58. }
  59. }
  60. }
  61. // Sort the list of IPs by their last octet value.
  62. sort.Sort(sort.Reverse(byLastOctetValue(nips)))
  63. return nips, nil
  64. }