-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (51 loc) · 1.17 KB
/
main.go
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
package main
import (
"bufio"
"log"
"net"
)
func main() {
//create new listener on all addresses on the port 1030
ln, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 1030})
//panic if listener failed
if err != nil {
log.Fatal(err)
return
}
//TODO: replace with actual feedback
println("listening on 0.0.0.0:1030")
for {
conn, err := ln.AcceptTCP()
if err != nil {
//ignore errors
break
}
//handle connection on new go routine
go handle(conn)
}
}
// handle incoming tcp connections
func handle(conn *net.TCPConn) {
//get remote address
addr := conn.RemoteAddr()
//convert address into IP & port combo
tcpaddr, err := net.ResolveTCPAddr(addr.Network(), addr.String())
if err != nil {
//this shouldn't happen, but just in case we close the socket
_ = conn.Close()
return
}
//create writer so we can chuck bytes
w := bufio.NewWriter(conn)
//write version number
_ = w.WriteByte(0x01)
_, _ = w.Write(tcpaddr.IP.To4())
//write port to buffer
port := uint16(tcpaddr.Port)
_ = w.WriteByte(byte(port))
_ = w.WriteByte(byte(port >> 8))
//flush buffer
_ = w.Flush()
//close connection
_ = conn.Close()
}