tcp.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package service
  2. import (
  3. "errors"
  4. "net"
  5. "strings"
  6. "sync"
  7. "time"
  8. )
  9. func ListenTcp() {
  10. var listen net.Listener
  11. var err error
  12. // 监听当前的tcp连接
  13. for {
  14. listen, err = net.Listen("tcp", "0.0.0.0:9200")
  15. if err != nil {
  16. time.Sleep(5 * time.Second) // 休眠一段时间后重试
  17. continue
  18. }
  19. break // 成功监听后退出循环
  20. }
  21. tracker := NewConnectionTracker() //创建连接检测器
  22. for {
  23. conn, err := listen.Accept()
  24. if err != nil {
  25. continue
  26. }
  27. err = CheckConn(conn, tracker)
  28. if err != nil {
  29. conn.Close() // 如果是恶意连接,则关闭连接
  30. continue
  31. }
  32. }
  33. }
  34. func CheckConn(conn net.Conn, tracker *ConnectionTracker) error {
  35. arr := strings.Split(conn.RemoteAddr().String(), ":")
  36. ip := arr[0]
  37. // 记录连接
  38. tracker.recordConnection(ip)
  39. // 检查是否为恶意连接
  40. if tracker.isMalicious(ip) {
  41. return errors.New("connection is Malicious")
  42. }
  43. device := Device{}
  44. device.Start(conn)
  45. return nil
  46. }
  47. type ConnectionTracker struct {
  48. mu sync.Mutex
  49. connections map[string][]time.Time // 存储每个 IP 的连接时间戳
  50. }
  51. func NewConnectionTracker() *ConnectionTracker {
  52. return &ConnectionTracker{
  53. connections: make(map[string][]time.Time),
  54. }
  55. }
  56. func (ct *ConnectionTracker) recordConnection(ip string) {
  57. ct.mu.Lock()
  58. defer ct.mu.Unlock()
  59. now := time.Now()
  60. ct.connections[ip] = append(ct.connections[ip], now)
  61. // 清理过期的连接记录
  62. ct.cleanUpExpired(ip, now)
  63. }
  64. func (ct *ConnectionTracker) cleanUpExpired(ip string, now time.Time) {
  65. threshold := now.Add(-3 * time.Minute)
  66. if timestamps, exists := ct.connections[ip]; exists {
  67. var filtered []time.Time
  68. for _, t := range timestamps {
  69. if t.After(threshold) { // 检查时间戳是否在三分钟内
  70. filtered = append(filtered, t) // 如果在范围内,保存到 filtered 列表
  71. }
  72. }
  73. ct.connections[ip] = filtered
  74. }
  75. }
  76. // 判断是否是恶意连接
  77. func (ct *ConnectionTracker) isMalicious(ip string) bool {
  78. ct.mu.Lock()
  79. defer ct.mu.Unlock()
  80. if timestamps, exists := ct.connections[ip]; exists {
  81. return len(timestamps) >= 10 // 定义恶意连接的阈值
  82. }
  83. return false
  84. }