-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
76 lines (71 loc) · 1.82 KB
/
tcp.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
70
71
72
73
74
75
76
package traffic_replicator
import (
"fmt"
"net"
)
// handleTCPConnection handles TCP connections
//
// Parameters:
//
// conn - the TCP connection
//
// Returns:
//
// None
func (tr *TrafficReplicator) handleTCPConnection(conn *net.TCPConn, port int) {
defer conn.Close()
var connMap = make(map[string]*net.TCPConn)
for _, targetIP := range tr.ReplicateTo {
destAddr := fmt.Sprintf("%s:%d", targetIP, port)
tcpAddr, err := net.ResolveTCPAddr("tcp", destAddr)
if err != nil {
fmt.Println("ResolveTCPAddr failed:", err)
continue
}
destConn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
fmt.Println("DialTCP failed:", err)
continue
}
defer destConn.Close()
connMap[targetIP] = destConn
}
buffer := make([]byte, 1024*1024)
go func() {
for {
// read from source
n, err := conn.Read(buffer)
if err != nil {
fmt.Errorf("read failed: %v", err)
return
}
fmt.Printf("Received TCP packet from %s, length: %v\n", conn.RemoteAddr().String(), n)
ShowPacket(buffer[:n], tr.ShowPacketAsASCII, tr.ShowPacketAsHex)
// write to all destinations
for targetIP, destConn := range connMap {
_, err = destConn.Write(buffer[:n])
if err != nil {
fmt.Errorf("write failed: %v", err)
return
}
fmt.Printf("Sent TCP packet to %s\n", targetIP)
}
}
}()
// read from first destination and write to source
for {
n, err := connMap[tr.ReplicateTo[0]].Read(buffer)
if err != nil {
fmt.Errorf("read failed: %v", err)
return
}
fmt.Printf("Received TCP packet from %s, length: %v\n", tr.ReplicateTo[0], n)
ShowPacket(buffer[:n], tr.ShowPacketAsASCII, tr.ShowPacketAsHex)
_, err = conn.Write(buffer[:n])
if err != nil {
fmt.Errorf("write failed: %v", err)
return
}
fmt.Printf("Sent TCP packet to %s,length: %v\n", conn.RemoteAddr().String(), n)
}
}