gipv4_lookup.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. //
  7. package gipv4
  8. import (
  9. "net"
  10. "strings"
  11. )
  12. // GetHostByName returns the IPv4 address corresponding to a given Internet host name.
  13. func GetHostByName(hostname string) (string, error) {
  14. ips, err := net.LookupIP(hostname)
  15. if ips != nil {
  16. for _, v := range ips {
  17. if v.To4() != nil {
  18. return v.String(), nil
  19. }
  20. }
  21. return "", nil
  22. }
  23. return "", err
  24. }
  25. // GetHostsByName returns a list of IPv4 addresses corresponding to a given Internet
  26. // host name.
  27. func GetHostsByName(hostname string) ([]string, error) {
  28. ips, err := net.LookupIP(hostname)
  29. if ips != nil {
  30. var ipStrings []string
  31. for _, v := range ips {
  32. if v.To4() != nil {
  33. ipStrings = append(ipStrings, v.String())
  34. }
  35. }
  36. return ipStrings, nil
  37. }
  38. return nil, err
  39. }
  40. // GetNameByAddr returns the Internet host name corresponding to a given IP address.
  41. func GetNameByAddr(ipAddress string) (string, error) {
  42. names, err := net.LookupAddr(ipAddress)
  43. if names != nil {
  44. return strings.TrimRight(names[0], "."), nil
  45. }
  46. return "", err
  47. }