net.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. )
  11. // GetInterfaceAddrs returns the IP networks of all interfaces that are up.
  12. // Point-to-point interfaces are exluded unless includePtP is true.
  13. func GetInterfaceAddrs(includePtP bool) ([]*net.IPNet, error) {
  14. intfs, err := net.Interfaces()
  15. if err != nil {
  16. return nil, err
  17. }
  18. var addrs []net.Addr
  19. for _, intf := range intfs {
  20. if intf.Flags&net.FlagRunning == 0 {
  21. continue
  22. }
  23. if !includePtP && intf.Flags&net.FlagPointToPoint != 0 {
  24. // Point-to-point interfaces are typically VPNs and similar
  25. // which, for our purposes, do not qualify as LANs.
  26. continue
  27. }
  28. intfAddrs, err := intf.Addrs()
  29. if err != nil {
  30. return nil, err
  31. }
  32. addrs = append(addrs, intfAddrs...)
  33. }
  34. nets := make([]*net.IPNet, 0, len(addrs))
  35. for _, addr := range addrs {
  36. net, ok := addr.(*net.IPNet)
  37. if ok {
  38. nets = append(nets, net)
  39. }
  40. }
  41. return nets, nil
  42. }
  43. func IPFromString(addr string) net.IP {
  44. // strip the port
  45. host, _, err := net.SplitHostPort(addr)
  46. if err != nil {
  47. host = addr
  48. }
  49. // strip IPv6 zone identifier
  50. host, _, _ = strings.Cut(host, "%")
  51. return net.ParseIP(host)
  52. }
  53. func IPFromAddr(addr net.Addr) (net.IP, error) {
  54. switch a := addr.(type) {
  55. case *net.TCPAddr:
  56. return a.IP, nil
  57. case *net.UDPAddr:
  58. return a.IP, nil
  59. default:
  60. host, _, err := net.SplitHostPort(addr.String())
  61. return net.ParseIP(host), err
  62. }
  63. }