从IP地址中获取域名的Go代码部分

huangapple go评论77阅读模式
英文:

Get domain name from IP address in Go

问题

我正在尝试从IP地址解析主机名,这似乎比我想象的要困难一些。

我尝试使用了几个函数,包括net.LookupHost方法,但它们似乎只返回我输入的IP地址。

这是我正在使用的代码:

package main

import (
	"fmt"
	"net"
)

func main() {
	// 从ping -c 1 stackoverflow.com获取,应该打印出"stackoverflow.com"
	addr, err := net.LookupHost("198.252.206.16")
	fmt.Println(addr, err)
}
英文:

I'm trying to resolve the host name from an IP address, which is apparently proving to be a little more challenging than I thought it'd be.

I've tried using a couple of functions, including the net.LookupHost method, but all of them seem to be just returning the IP address which I input.

Here's the code which I am using:

package main

import (
	"fmt"
	"net"
)

func main() {
	// obtained from ping -c 1 stackoverflow.com, should print "stackoverflow.com"
	addr, err := net.LookupHost("198.252.206.16")
	fmt.Println(addr, err)
}

答案1

得分: 21

例如,

package main

import (
	"fmt"
	"net"
)

func main() {
	// 从 ping -c 1 stackoverflow.com 获取,应该打印 "stackoverflow.com"
	addr, err := net.LookupAddr("198.252.206.16")
	fmt.Println(addr, err)
}

输出:

[stackoverflow.com.] <nil>
英文:

For example,

package main

import (
	&quot;fmt&quot;
	&quot;net&quot;
)

func main() {
	// obtained from ping -c 1 stackoverflow.com, should print &quot;stackoverflow.com&quot;
	addr, err := net.LookupAddr(&quot;198.252.206.16&quot;)
	fmt.Println(addr, err)
}

Output:

[stackoverflow.com.] &lt;nil&gt;

答案2

得分: 4

您需要使用LookupAddr而不是LookupHost。

英文:

You need LookupAddr instead of LookupHost.

huangapple
  • 本文由 发表于 2013年5月13日 06:49:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/16512840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定