SoFunction
Updated on 2025-03-04

Implement application IP firewall based on Go language

Introduction

In the company, you often hear that an application has security vulnerabilities and has not been used for security reinforcement. IP firewall is a typical security reinforcement solution. Only specified IP segments are allowed to access the application, which is generally an intranet IP

This article mainly explains how to implement IP firewall in Go language

Standard library implementation

In fact, the net package of Go has corresponding implementations, we only need simple applications.

The source code is as follows

// ParseCIDR parses s as a CIDR notation IP address and prefix length,
// like "192.0.2.0/24" or "2001:db8::/32", as defined in
// RFC 4632 and RFC 4291.
//
// It returns the IP address and the network implied by the IP and
// prefix length.
// For example, ParseCIDR("192.0.2.1/24") returns the IP address
// 192.0.2.1 and the network 192.0.2.0/24.
func ParseCIDR(s string) (IP, *IPNet, error)

It means that we can set an IP segment, for example, 192.0.2.1/24, then 192.0.2.1 will be within this range, while 192.0.3.1 will not be within this range, and corresponding processing should be done.

Code implementation

package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {
	ipWall := NewFireWall()
	// Set up the IP segment that can access the application	("127.0.0.1")
	("192.0.2.1/24")
	("2001:db8::/32") // Can support ipv6
	// test	("127.0.0.1", ("127.0.0.1"))
	("192.0.2.10", ("192.0.2.10"))
	("192.0.3.10", ("192.0.3.10"))
	("2001:db8::1", ("2001:db8::1"))
	("2001:db9::1", ("2001:db9::1"))

}

// Define the firewall and save the rules nodes
type FireWall struct {
	nodes []
}

func NewFireWall() *FireWall {
	return &FireWall{
		nodes: make([], 0),
	}
}

// Add rules
func (b *FireWall) ParseNode(line string) {
	if !(line, "/") {
		parsedIP := (line)

		if ipv4 := parsedIP.To4(); ipv4 != nil {
			// return ip in a 4-byte representation
			parsedIP = ipv4
		}
		if parsedIP != nil {
			switch len(parsedIP) {
			case net.IPv4len:
				line += "/32"
			case net.IPv6len:
				line += "/128"
			}
		}
	}
	_, cidrNet, err := (line)
	if err == nil {
		 = append(, *cidrNet)
	}
}

// Check that an IP is not in the set rules
func (b *FireWall) Check(ip string) bool {
	for _, cidr := range  {
		remoteIP := (ip)
		if (remoteIP) {
			return true
		}
	}
	return false
}

Execute the above code and output

127.0.0.1 true
192.0.2.10 true
192.0.3.10 false
2001:db8::1 true
2001:db9::1 false

The above is the implementation of the IP firewall, which is also implemented in the gin framework.

This is the end of this article about implementing IP firewall application based on Go language. For more related Go IP firewall content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!