-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (76 loc) · 1.69 KB
/
Copy pathmain.go
File metadata and controls
88 lines (76 loc) · 1.69 KB
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
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"time"
)
func main() {
Sample("IPv4", IPv4)
Sample("LookupIP", LookupIP)
Sample("ParseIP", ParseIP)
Sample("Listener", Listener)
Sample("Dialer", Dialer)
}
func IPv4() {
fmt.Println(net.IPv4(8, 8, 8, 8))
}
func LookupIP() {
ips, err := net.LookupIP("golang.org")
if err != nil {
fmt.Println("error:", err)
}
for _, ip := range ips {
fmt.Println(ip)
}
}
func ParseIP() {
fmt.Println(net.ParseIP("192.0.2.1")) // 192.0.2.1
fmt.Println(net.ParseIP("2001:db8::68")) // 2001:db8::68
fmt.Println(net.ParseIP("192.0.2")) // nil
}
func Listener() {
// 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 Dialer() {
var d net.Dialer
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
conn, err := d.DialContext(ctx, "tcp", ":2000")
if err != nil {
fmt.Println("error:", err)
}
defer conn.Close()
if _, err := conn.Write([]byte("Hello, World!")); err != nil {
fmt.Println("error:", err)
}
}
func Sample(name string, fn func()) {
fmt.Println(">", name)
fn()
fmt.Println()
}