net.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. )
  10. func GetLans() ([]*net.IPNet, error) {
  11. ifs, err := net.Interfaces()
  12. if err != nil {
  13. return nil, err
  14. }
  15. var addrs []net.Addr
  16. for _, currentIf := range ifs {
  17. if currentIf.Flags&net.FlagRunning == 0 {
  18. continue
  19. }
  20. currentAddrs, err := currentIf.Addrs()
  21. if err != nil {
  22. return nil, err
  23. }
  24. addrs = append(addrs, currentAddrs...)
  25. }
  26. nets := make([]*net.IPNet, 0, len(addrs))
  27. for _, addr := range addrs {
  28. net, ok := addr.(*net.IPNet)
  29. if ok {
  30. nets = append(nets, net)
  31. }
  32. }
  33. return nets, nil
  34. }
  35. func IPFromAddr(addr net.Addr) (net.IP, error) {
  36. switch a := addr.(type) {
  37. case *net.TCPAddr:
  38. return a.IP, nil
  39. case *net.UDPAddr:
  40. return a.IP, nil
  41. default:
  42. host, _, err := net.SplitHostPort(addr.String())
  43. return net.ParseIP(host), err
  44. }
  45. }