tcp.go 2.2 KB

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