go语言web编程,初学点滴记录1
明述道长 · · 4182 次点击 · · 开始浏览几乎所有代码都来自:
http://jan.newmarch.name/go/
感谢该作者
/* IP
*/
package main
import (
"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 main
import (
"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 www.baidu.com
得到结果: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.
嘿嘿
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
几乎所有代码都来自:
http://jan.newmarch.name/go/
感谢该作者
/* IP
*/
package main
import (
"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 main
import (
"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 www.baidu.com
得到结果: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.
嘿嘿