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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package net_test
import (
"fmt"
"io"
"log"
"net"
)
func ExampleListener() {
// Listen on TCP port 2000 on all available unicast and
// anycast IP addresses of the local system.
l, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// Wait for a connection.
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// Handle the connection in a new goroutine.
// The loop then returns to accepting, so that
// multiple connections may be served concurrently.
go func(c net.Conn) {
// Echo all incoming data.
io.Copy(c, c)
// Shut down the connection.
c.Close()
}(conn)
}
}
func ExampleIPv4() {
fmt.Println(net.IPv4(8, 8, 8, 8))
// Output:
// 8.8.8.8
}
func ExampleParseCIDR() {
ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")
if err != nil {
log.Fatal(err)
}
fmt.Println(ipv4Addr)
fmt.Println(ipv4Net)
ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")
if err != nil {
log.Fatal(err)
}
fmt.Println(ipv6Addr)
fmt.Println(ipv6Net)
// Output:
// 192.0.2.1
// 192.0.2.0/24
// 2001:db8:a0b:12f0::1
// 2001:db8::/32
}
func ExampleParseIP() {
fmt.Println(net.ParseIP("192.0.2.1"))
fmt.Println(net.ParseIP("2001:db8::68"))
fmt.Println(net.ParseIP("192.0.2"))
// Output:
// 192.0.2.1
// 2001:db8::68
// <nil>
}
func ExampleIP_DefaultMask() {
ip := net.ParseIP("192.0.2.1")
fmt.Println(ip.DefaultMask())
// Output:
// ffffff00
}
func ExampleIP_Mask() {
ipv4Addr := net.ParseIP("192.0.2.1")
// This mask corresponds to a /24 subnet for IPv4.
ipv4Mask := net.CIDRMask(24, 32)
fmt.Println(ipv4Addr.Mask(ipv4Mask))
ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1")
// This mask corresponds to a /32 subnet for IPv6.
ipv6Mask := net.CIDRMask(32, 128)
fmt.Println(ipv6Addr.Mask(ipv6Mask))
// Output:
// 192.0.2.0
// 2001:db8::
}
func ExampleCIDRMask() {
// This mask corresponds to a /31 subnet for IPv4.
fmt.Println(net.CIDRMask(31, 32))
// This mask corresponds to a /64 subnet for IPv6.
fmt.Println(net.CIDRMask(64, 128))
// Output:
// fffffffe
// ffffffffffffffff0000000000000000
}
func ExampleIPv4Mask() {
fmt.Println(net.IPv4Mask(255, 255, 255, 0))
// Output:
// ffffff00
}
|