github.com/wangyougui/gf/v2@v2.6.5/net/gipv4/gipv4_lookup.go (about) 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/wangyougui/gf. 6 // 7 8 package gipv4 9 10 import ( 11 "net" 12 "strings" 13 ) 14 15 // GetHostByName returns the IPv4 address corresponding to a given Internet host name. 16 func GetHostByName(hostname string) (string, error) { 17 ips, err := net.LookupIP(hostname) 18 if ips != nil { 19 for _, v := range ips { 20 if v.To4() != nil { 21 return v.String(), nil 22 } 23 } 24 return "", nil 25 } 26 return "", err 27 } 28 29 // GetHostsByName returns a list of IPv4 addresses corresponding to a given Internet 30 // host name. 31 func GetHostsByName(hostname string) ([]string, error) { 32 ips, err := net.LookupIP(hostname) 33 if ips != nil { 34 var ipStrings []string 35 for _, v := range ips { 36 if v.To4() != nil { 37 ipStrings = append(ipStrings, v.String()) 38 } 39 } 40 return ipStrings, nil 41 } 42 return nil, err 43 } 44 45 // GetNameByAddr returns the Internet host name corresponding to a given IP address. 46 func GetNameByAddr(ipAddress string) (string, error) { 47 names, err := net.LookupAddr(ipAddress) 48 if names != nil { 49 return strings.TrimRight(names[0], "."), nil 50 } 51 return "", err 52 }