netutil.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package netutil
  14. import (
  15. "log"
  16. "net"
  17. "net/url"
  18. )
  19. var (
  20. // indirection for testing
  21. resolveTCPAddr = net.ResolveTCPAddr
  22. )
  23. // ResolveTCPAddrs is a convenience wrapper for net.ResolveTCPAddr.
  24. // ResolveTCPAddrs resolves all DNS hostnames in-place for the given set of
  25. // url.URLs.
  26. func ResolveTCPAddrs(urls ...[]url.URL) error {
  27. for _, us := range urls {
  28. for i, u := range us {
  29. host, _, err := net.SplitHostPort(u.Host)
  30. if err != nil {
  31. log.Printf("netutil: Could not parse url %s during tcp resolving.", u.Host)
  32. return err
  33. }
  34. if host == "localhost" {
  35. continue
  36. }
  37. if net.ParseIP(host) != nil {
  38. continue
  39. }
  40. tcpAddr, err := resolveTCPAddr("tcp", u.Host)
  41. if err != nil {
  42. log.Printf("netutil: Could not resolve host: %s", u.Host)
  43. return err
  44. }
  45. log.Printf("netutil: Resolving %s to %s", u.Host, tcpAddr.String())
  46. us[i].Host = tcpAddr.String()
  47. }
  48. }
  49. return nil
  50. }