独角兽企业重金招聘Python工程师标准>>>
几乎所有代码都来自:
http://jan.newmarch.name/go/
感谢该作者
/* IP*/package mainimport ("fmt""net""os")func main() {if len(os.Args) != 2 {fmt.Fprintf(os.Stderr, "Usage: %s ip-addr\n", os.Args[0])os.Exit(1)}name := os.Args[1]addr := net.ParseIP(name)if addr == nil {fmt.Println("Invalid address")} else {fmt.Println("The address is ", addr.String())}os.Exit(0)}
主要用到了net包。
os.Args是命令行参数
是个string的slice切片
net.ParseIP()顾名思意就是转换成IP地址其实也就是把"192.168.1.1"这样的字符串转换成go语言中ip的形式,go语言中ip是[]byte类型的,这事一个slice切片。这个程序或许没多大用处,但是下面这个改过的版本可能有点用处:
/* IP*/package mainimport ("fmt""net""os")func main() {if len(os.Args) != 2 {fmt.Fprintf(os.Stderr, "Usage: %s ip-addr\n", os.Args[0])os.Exit(1)}name := os.Args[1]//addr := net.ParseIP(name)addr, _:=net.LookupHost(name)if addr[0] == "" {fmt.Println("Invalid address")} else {fmt.Println("The address is "+addr[0])}os.Exit(0)}
编译成功后:运行./ip
得到结果:The address is 123.125.114.144
net.LookupHost() 查看域名的ip地址,官方解释是:LookupHost looks up the given host using the local resolver. It returns an array of that host's addresses.
嘿嘿