golang read hosts entry or just read it in as a file

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

golang read hosts entry or just read it in as a file

问题

我需要从Linux主机文件中读取一个条目。

我已经查看了"net"

fmt.Println("net主机文件条目:")
fmt.Println(net.LookupIP("AAA"))
fmt.Println(net.LookupAddr("BBB"))
fmt.Println(net.LookupHost("CCC"))

net.LookupIP("AAA")给我返回了:"no such host"。

尽管我可以在终端上使用getent hosts命令看到该条目。

我只需要读取IP地址吗?

注意:我是在Docker容器中运行这个程序,etc/hosts文件中确实包含该条目 - 我可以从shell脚本中读取它,但无法从Go中读取。
在Docker中,你可以链接容器,这将在hosts文件中给你一个条目。

或者我应该将其作为文件读取?

英文:

I need to read an entry from the host file on Linux.

I have looked at "net"

fmt.Println("net host file entry:")
fmt.Println(net.LookupIP("AAA"))
fmt.Println(net.LookupAddr("BBB"))
fmt.Println(net.LookupHost("CCC"))

net.LookupIP("AAA") gives me: no such host.
<br>
<br>
Though I can see the entry if I do getent hosts from the terminal.

I just need to read the ip address?

Note: I am running this within a docker container and the etc/hosts file do contain the entry - I can read it from a shell script but not from go.
In docker you can link containers and this will give you an entry in the hosts file.

Or should I just read it in as a file?

答案1

得分: 1

如果你只想读取文件...

导入 (
"fmt"
"io/ioutil"
)

然后

dat, err := ioutil.ReadFile("/windows/system32/drivers/etc/hosts")
fmt.Print(string(dat))

你可以解析结果。

英文:

If you want to just read the file...

import (
"fmt"
"io/ioutil"
)

and then

dat, err := ioutil.ReadFile(&quot;/windows/system32/drivers/etc/hosts&quot;)
fmt.Print(string(dat))

you can parse the result of course

huangapple
  • 本文由 发表于 2015年10月8日 02:30:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/32999850.html
匿名

发表评论

匿名网友

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

确定