networkInterface.go 1.9 KB

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