networkInterface.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "errors"
  22. "net"
  23. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  24. )
  25. // Take in an interface name ("lo", "eth0", "any") passed from either
  26. // a config setting, by using the -listenInterface flag on client or
  27. // -interface flag on server from the command line and return the IP
  28. // address associated with it.
  29. // If no interface is provided use the default loopback interface (127.0.0.1).
  30. // If "any" is passed then listen on 0.0.0.0 for client (invalid with server)
  31. func GetInterfaceIPAddress(listenInterface string) (string, error) {
  32. var ip net.IP
  33. if listenInterface == "" {
  34. ip = net.ParseIP("127.0.0.1")
  35. return ip.String(), nil
  36. } else if listenInterface == "any" {
  37. ip = net.ParseIP("0.0.0.0")
  38. return ip.String(), nil
  39. } else {
  40. availableInterfaces, err := net.InterfaceByName(listenInterface)
  41. if err != nil {
  42. return "", common.ContextError(err)
  43. }
  44. addrs, err := availableInterfaces.Addrs()
  45. if err != nil {
  46. return "", common.ContextError(err)
  47. }
  48. for _, addr := range addrs {
  49. iptype := addr.(*net.IPNet)
  50. if iptype == nil {
  51. continue
  52. }
  53. // TODO: IPv6 support
  54. ip = iptype.IP.To4()
  55. if ip == nil {
  56. continue
  57. }
  58. return ip.String(), nil
  59. }
  60. }
  61. return "", common.ContextError(errors.New("Could not find IP address of specified interface"))
  62. }