How to implement ban on frequent IP access in Golang

PHPz
Release: 2023-04-25 10:24:39
Original
1134 people have browsed it

In application development, prohibiting frequent access is a key security measure that can help you prevent various attacks, such as DDOS attacks. This article will introduce how to use Golang to write a simple program to prohibit frequent access to IP addresses.

Implementation ideas

The implementation method of prohibiting frequent access of IP addresses is mainly achieved by limiting the number of accesses to each IP address. The specific ideas are as follows:

  1. Create a map to record the number of visits to each IP address.
  2. When an IP address accesses our application, increase the value of the IP address's counter in the map.
  3. If we find that the counter of the IP address has exceeded the specified limit times, we will blacklist the IP address and prohibit access to our application.
  4. You can set the timeout of the counter to ensure that the blacklist of IP addresses does not last too long.

Code implementation

The following is a code example using Golang to implement the above idea:

package main

import (
    "fmt"
    "net"
    "sync"
    "time"
)

const (
    MaxRequestsPerIP = 10      // 每个IP最大请求数
    BlacklistTimeout = 60 * 5  // 黑名单超时时间(秒)
)

type IPRequests struct {
    Requests   int       // 请求计数器
    LastAccess time.Time // 最后一次访问时间
}

var (
    lock         sync.RWMutex
    ipRequestMap = make(map[string]*IPRequests)
    blacklist    = make(map[string]time.Time)
)

// 判断IP是否在黑名单内
func isBlacklisted(ip string) bool {
    lock.RLock()
    defer lock.RUnlock()
    if blacklistedTime, ok := blacklist[ip]; ok {
        if time.Since(blacklistedTime) < time.Second*BlacklistTimeout {
            return true
        } else {
            // 超时,从黑名单中删除 
            lock.Lock()
            delete(blacklist, ip)
            lock.Unlock()
        }
    }
    return false
}

// 记录IP访问次数
func recordIPRequest(ip string) {
    lock.Lock()
    defer lock.Unlock()
    req, ok := ipRequestMap[ip]
    if !ok {
        req = &IPRequests{}
        ipRequestMap[ip] = req
    }
    req.Requests++
    req.LastAccess = time.Now()
    // 如果IP访问次数过多,将其列入黑名单
    if req.Requests > MaxRequestsPerIP {
        blacklist[ip] = time.Now()
    }
}

// 启动HTTP服务器
func StartHttpServer() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        ip, _, _ := net.SplitHostPort(r.RemoteAddr)
        // 如果IP地址在黑名单内,则拒绝访问
        if isBlacklisted(ip) {
            http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
            return
        }
        // 记录IP地址的访问次数
        recordIPRequest(ip)
        // 处理请求
        fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
    })
    http.ListenAndServe(":8080", nil)
}

func main() {
    StartHttpServer()
}
Copy after login

In the above code, we use a map (ipRequestMap) to record The number of visits to each IP address, a map (blacklist) to store blacklist information. When an IP address accesses our application, we first check whether the IP address is in the blacklist, and if so, return 403 Access Forbidden. If not, record the number of visits to the IP address. When the number of visits to an IP address exceeds the specified threshold (MaxRequestsPerIP), we blacklist the IP address and prohibit access to our application.

In the isBlacklisted() function, we determine whether an IP is in the blacklist. If so, return true, telling the StartHttpServer() function that we should reject requests from that IP. At the same time, if the IP has exceeded the blacklist timeout (BlacklistTimeout), it will be deleted from the blacklist.

In the recordIPRequest() function, we use RWMutex (RW mutex lock) to ensure concurrency safety. This function is used to record the number of times an IP address is accessed. If the IP reaches the limit we set, it will be blacklisted.

Summary

The method to use Golang to ban frequent IP access is very simple. We only need to implement a counter and a blacklist. But in practice, we need to set appropriate thresholds according to our own needs. In the example of this article, we use two thresholds: the maximum number of requests (MaxRequestsPerIP) and the blacklist timeout (BlacklistTimeout). In practice, you can set a more appropriate threshold according to the specific situation.

The above is the detailed content of How to implement ban on frequent IP access in Golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!