networkInterface.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // Take in an interface name ("lo", "eth0", "any") passed from either
  24. // a config setting or by -interface command line flag and return the IP
  25. // address associated with it.
  26. // If no interface is provided use the default loopback interface (127.0.0.1).
  27. // If "any" is passed then listen on 0.0.0.0
  28. func GetInterfaceIPAddress(listenInterface string) (string, error) {
  29. var ip net.IP
  30. if listenInterface == "" {
  31. ip = net.ParseIP("127.0.0.1")
  32. } else if listenInterface == "any" {
  33. ip = net.ParseIP("0.0.0.0")
  34. } else {
  35. //Get a list of interfaces
  36. availableInterfaces, err := net.Interfaces()
  37. if err != nil {
  38. return "", ContextError(err)
  39. }
  40. var selectedInterface net.Interface
  41. found := false
  42. for _, networkInterface := range availableInterfaces {
  43. if listenInterface == networkInterface.Name {
  44. NoticeInfo("Using interface: %s", networkInterface.Name)
  45. selectedInterface = networkInterface
  46. found = true
  47. break
  48. }
  49. }
  50. if !found {
  51. NoticeAlert("Interface not found: %s", listenInterface)
  52. ip = net.ParseIP("127.0.0.1")
  53. } else {
  54. netAddrs, err := selectedInterface.Addrs()
  55. if err != nil {
  56. return "", ContextError(err)
  57. }
  58. for _, ipAddr := range netAddrs {
  59. ip, _, err = net.ParseCIDR(ipAddr.String())
  60. if err != nil {
  61. return "", ContextError(err)
  62. }
  63. if ip.To4() != nil {
  64. break
  65. }
  66. }
  67. }
  68. }
  69. NoticeInfo("Listening on IP address: %s", ip.String())
  70. return ip.String(), nil
  71. }