package src import ( "fmt" "strings" "sync" "time" ) // EventCounter is a structure to keep track of events. type EventCounter struct { counts map[string]int mutex sync.Mutex resetTimer *time.Ticker resetPeriod time.Duration alertHandler func(ip, port string, count int) } // NewEventCounter creates a new EventCounter instance. func NewEventCounter(resetPeriod time.Duration, alertHandler func(ip, port string, count int)) *EventCounter { return &EventCounter{ counts: make(map[string]int), resetTimer: time.NewTicker(resetPeriod), resetPeriod: resetPeriod, alertHandler: alertHandler, } } // CountEvent increments the count for a specific IP and port combination. func (ec *EventCounter) CountEvent(ip, port string) { key := ip + ":" + port ec.mutex.Lock() ec.counts[key]++ ec.mutex.Unlock() } // StartMonitoring starts the event monitoring and alerts. func (ec *EventCounter) StartMonitoring() { for range ec.resetTimer.C { ec.mutex.Lock() for key, count := range ec.counts { if count >= 100 { ip, port := parseKey(key) ec.alertHandler(ip, port, count) } } ec.resetCounts() ec.mutex.Unlock() } } func parseKey(key string) (string, string) { parts := strings.Split(key, ":") if len(parts) == 2 { return parts[0], parts[1] } return "", "" } func (ec *EventCounter) resetCounts() { ec.counts = make(map[string]int) } // StopMonitoring stops the event monitoring. func (ec *EventCounter) StopMonitoring() { ec.resetTimer.Stop() } // HandleAlert is a placeholder for alert handling logic. func HandleAlert(ip, port string, count int) { fmt.Printf("Alert: Source IP %s, Port %s exceeded the threshold with a count of %d\n", ip, port, count) }