net.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package osutil
  7. import (
  8. "net"
  9. "strings"
  10. "github.com/syncthing/syncthing/lib/netutil"
  11. )
  12. // GetInterfaceAddrs returns the IP networks of all interfaces that are up.
  13. // Point-to-point interfaces are excluded unless includePtP is true.
  14. func GetInterfaceAddrs(includePtP bool) ([]*net.IPNet, error) {
  15. intfs, err := netutil.Interfaces()
  16. if err != nil {
  17. return nil, err
  18. }
  19. var addrs []net.Addr
  20. for i := range intfs {
  21. intf := intfs[i]
  22. if intf.Flags&net.FlagRunning == 0 {
  23. continue
  24. }
  25. if !includePtP && intf.Flags&net.FlagPointToPoint != 0 {
  26. // Point-to-point interfaces are typically VPNs and similar
  27. // which, for our purposes, do not qualify as LANs.
  28. continue
  29. }
  30. intfAddrs, err := netutil.InterfaceAddrsByInterface(&intf)
  31. if err != nil {
  32. return nil, err
  33. }
  34. addrs = append(addrs, intfAddrs...)
  35. }
  36. nets := make([]*net.IPNet, 0, len(addrs))
  37. for _, addr := range addrs {
  38. net, ok := addr.(*net.IPNet)
  39. if ok {
  40. nets = append(nets, net)
  41. }
  42. }
  43. return nets, nil
  44. }
  45. func IPFromString(addr string) net.IP {
  46. // strip the port
  47. host, _, err := net.SplitHostPort(addr)
  48. if err != nil {
  49. host = addr
  50. }
  51. // strip IPv6 zone identifier
  52. host, _, _ = strings.Cut(host, "%")
  53. return net.ParseIP(host)
  54. }
  55. func IPFromAddr(addr net.Addr) (net.IP, error) {
  56. switch a := addr.(type) {
  57. case *net.TCPAddr:
  58. return a.IP, nil
  59. case *net.UDPAddr:
  60. return a.IP, nil
  61. default:
  62. host, _, err := net.SplitHostPort(addr.String())
  63. return net.ParseIP(host), err
  64. }
  65. }