net.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 http://mozilla.org/MPL/2.0/.
  6. package osutil
  7. import (
  8. "bytes"
  9. "net"
  10. )
  11. // ResolveInterfaceAddresses returns available addresses of the given network
  12. // type for a given interface.
  13. func ResolveInterfaceAddresses(network, nameOrMac string) []string {
  14. intf, err := net.InterfaceByName(nameOrMac)
  15. if err == nil {
  16. return interfaceAddresses(network, intf)
  17. }
  18. mac, err := net.ParseMAC(nameOrMac)
  19. if err != nil {
  20. return []string{nameOrMac}
  21. }
  22. intfs, err := net.Interfaces()
  23. if err != nil {
  24. return []string{nameOrMac}
  25. }
  26. for _, intf := range intfs {
  27. if bytes.Equal(intf.HardwareAddr, mac) {
  28. return interfaceAddresses(network, &intf)
  29. }
  30. }
  31. return []string{nameOrMac}
  32. }
  33. func interfaceAddresses(network string, intf *net.Interface) []string {
  34. var out []string
  35. addrs, err := intf.Addrs()
  36. if err != nil {
  37. return out
  38. }
  39. for _, addr := range addrs {
  40. ipnet, ok := addr.(*net.IPNet)
  41. if ok && (network == "tcp" || (network == "tcp4" && len(ipnet.IP) == net.IPv4len) || (network == "tcp6" && len(ipnet.IP) == net.IPv6len)) {
  42. out = append(out, ipnet.IP.String())
  43. }
  44. }
  45. return out
  46. }