go语言渐入佳境-网络[1]-ipaddress

net包中的ip类型存储ip地址

type IP []byte

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* IP
*/

package main

import (
"net"
"os"
"fmt"
)

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)
}

测试:

1
2
3
$ go build .
$ ./net 127.0.0.1
The address is 127.0.0.1