networkInterface.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package common
  20. import (
  21. "fmt"
  22. "net"
  23. )
  24. // GetInterfaceIPAddresses takes an interface name, such as "eth0", and returns
  25. // the first IPv4 and IPv6 addresses associated with it. Either of the IPv4 or
  26. // IPv6 address may be nil. If neither type of address is found, an error
  27. // is returned.
  28. func GetInterfaceIPAddresses(interfaceName string) (net.IP, net.IP, error) {
  29. var IPv4Address, IPv6Address net.IP
  30. availableInterfaces, err := net.InterfaceByName(interfaceName)
  31. if err != nil {
  32. return nil, nil, ContextError(err)
  33. }
  34. addrs, err := availableInterfaces.Addrs()
  35. if err != nil {
  36. return nil, nil, ContextError(err)
  37. }
  38. for _, addr := range addrs {
  39. ipNet := addr.(*net.IPNet)
  40. if ipNet == nil {
  41. continue
  42. }
  43. if ipNet.IP.To4() != nil {
  44. if IPv4Address == nil {
  45. IPv4Address = ipNet.IP
  46. }
  47. } else {
  48. if IPv6Address == nil {
  49. IPv6Address = ipNet.IP
  50. }
  51. }
  52. if IPv4Address != nil && IPv6Address != nil {
  53. break
  54. }
  55. }
  56. if IPv4Address != nil || IPv6Address != nil {
  57. return IPv4Address, IPv6Address, nil
  58. }
  59. return nil, nil, ContextError(fmt.Errorf("Could not find any IP address for interface %s", interfaceName))
  60. }