networkInterface.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 psiphon
  20. import (
  21. "net"
  22. )
  23. func GetInterfaceIPAddress(interfaceName string) string {
  24. var selectedInterface net.Interface
  25. var ip net.IP
  26. //Get a list of interfaces
  27. availableInterfaces, err := net.Interfaces()
  28. if err != nil {
  29. NoticeAlert("%s", ContextError(err))
  30. }
  31. if interfaceName == "any" {
  32. ip = net.ParseIP("0.0.0.0")
  33. } else {
  34. for _, networkInterface := range availableInterfaces {
  35. if interfaceName == networkInterface.Name {
  36. NoticeAlert("Using interface: %s", networkInterface.Name)
  37. selectedInterface = networkInterface
  38. break
  39. }
  40. }
  41. }
  42. if ip.To4() == nil {
  43. if selectedInterface.Name == "" {
  44. selectedInterface = availableInterfaces[0]
  45. NoticeAlert("No interface found, using %s", selectedInterface.Name)
  46. }
  47. }
  48. netAddrs, err := selectedInterface.Addrs()
  49. if err != nil {
  50. NoticeAlert("Error : %s", err.Error())
  51. }
  52. for _, ipAddr := range netAddrs {
  53. ip, _, err = net.ParseCIDR(ipAddr.String())
  54. if err != nil {
  55. NoticeAlert("Error parsing address %s", err.Error())
  56. }
  57. if ip.To4() != nil {
  58. break
  59. }
  60. }
  61. return ip.String()
  62. }