Go language RPC Authorization simple ip security verification method

  • 2020-05-17 05:40:47
  • OfStack

This article illustrates a simple ip security verification method for Go language RPC Authorization. Share with you for your reference. The specific analysis is as follows:

To write a network service, always consider the security mechanism, ip and network segment to judge is the simplest 1 verification mechanism. After that, I want to make a security verification mechanism similar to the registration, which can not only reduce the trouble of configuration files, but also can be a good security management.

Direct access code:

package main
import(
    "net"
    "fmt"
    "time"
    "strings"
)
func main(){
    IP_ARRAY := "192.168.1.234,192.168.1.47,192.168.2.0/28"
    servPort:=":7272"
    l,err := net.Listen( "tcp",servPort )
    if err != nil {
        fmt.Printf( "Listen is error" )
        return
    }
    allowList :=strings.Split( IP_ARRAY,"," )
    for{
        conn,err:=l.Accept()
        if err != nil {
            fmt.Printf( "start connect  is error" )
            return
        }
        ipAddr:=conn.RemoteAddr()
        Addr := strings.Split( ipAddr.String(), ":")
        rAddr := net.ParseIP( Addr[0] )
        var authorized bool = false
        for v := range allowList{
            _,ipNet,err := net.ParseCIDR( allowList[v] )
            if err != nil{
                fmt.Printf( "parse ip net error" )
                ipHost := net.ParseIP( allowList[v])
                if ipHost != nil{
                   if ipHost.Equal( rAddr ) {
                      authorized =true
                   }
                }else{
                    fmt.Printf( "ip list error" )
                }
            }else{
                fmt.Printf( "Contains ip " )
                if ipNet.Contains( rAddr ) {
                    authorized =true
                }
            }
        }
        if authorized == true{
            curTime:=time.Now()
            fmt.Printf( curTime.Format( "2006-01-02 15:04:05" )  )
            conn.Write( []byte(curTime.Format( "2006-01-02 15:04:05" ) ) )
            time.Sleep( 10)
        }else{
            conn.Close()
        }
    }
}

I hope this article has been helpful to your programming of Go language.


Related articles: