过去几天我开始选择 Go,主要依赖于语言规范和包文档,但是我在解读 net.LookupNS 的正确用法时遇到了问题。 由于它是指针类型,返回 NS 服务器值的内存地址数组,因此我想访问实际值/取消引用该数组。
计划:
package main
import "fmt"
import "net"
import "os"
var host string
func args() {
if len(os.Args) != 2 {
fmt.Println("You need to enter a host!")
} else {
host = os.Args[1]
}
if host == "" {
os.Exit(0)
}
}
func nslookup() []*net.NS {
nserv, err := net.LookupNS(host)
if err != nil {
fmt.Println("Error occured during NS lookup", err)
}
return *&nserv
}
func main() {
args()
fmt.Println("Nameserver information:", host)
fmt.Println(" NS records:", nslookup())
}
给定例如google.com,它显示以下内容:
Nameserver information: google.com
NS records: [0xc2100376f0 0xc210037700 0xc210037710 0xc210037720]
我想查看取消引用的值,而不是内存地址位置,例如:
NS records: ["ns1.google.com", "ns2.google.com", "ns3.google.com", "ns4.google.com"]
现在显然,我更喜欢将它们作为字符串数组/slice ,但问题是我可以获得实际名称服务器的唯一方法如下:
func nslookup() *net.NS {
// The rest of the function
return *&nserv[0] // This returns the first nameserver
上面返回以下内容:
Nameserver information: google.com
NS records: &{ns1.google.com.}
虽然这至少返回实际值而不是内存地址,但它需要索引,这不是很灵活,而且它的格式不是非常用户友好的格式。 此外,无法将 []*net.NS 结构直接转换为字符串。
问题: 如何获取名称服务器数组,而不是内存地址,最好是字符串数组/slice ?
最佳答案
好吧,有几个问题:
为什么要返回
*&nserv
? Go 不是 C,请停止你正在做的一切并阅读 Effective Go .您的
nslookup
函数返回一个*net.NS
片段,这是一个指针片段,因此fmt.Println
是打印正确的内容,如果您想要更多详细信息,可以使用fmt.Printf
使用%#v
或%#q
修饰符查看数据的实际外观。
示例:
package main
import "fmt"
import "net"
import "os"
var host string
func nslookupString(nserv []*net.NS) (hosts []string) {
hosts = make([]string, len(nserv))
for i, host := range nserv {
hosts[i] = host.Host
}
return
}
func nslookupNS(host string) []*net.NS {
nserv, err := net.LookupNS(host)
if err != nil {
fmt.Println("Error occured during NS lookup", err)
}
return nserv
}
func init() { //initilizing global arguments is usually done in init()
if len(os.Args) == 2 {
host = os.Args[1]
}
}
func main() {
if host == "" {
fmt.Println("You need to enter a host!")
os.Exit(1)
}
fmt.Println("Nameserver information:", host)
ns := nslookupNS(host)
fmt.Printf(" NS records String: %#q\n", nslookupString(ns))
fmt.Printf(" NS records net.NS: %q\n", ns)
for _, h := range ns {
fmt.Printf("%#v\n", h)
}
}
关于pointers - 无法正确取消引用指针并从内存地址数组中获取实际值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106253/