本文实例讲述了Go语言RPC Authorization进行简单ip安全验证的方法。分享给大家供大家参考。具体分析如下:
前言:写网络服务,总要考虑安全机制,对ip和网段进行判断是最简单的一个验证机制。之后想做一个类似注册式的安全验证机制,既可以减少配置文件的麻烦,又可以很好的进行安全管理。
直接上代码:
复制代码 代码如下:
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()
}
}
}
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()
}
}
}
希望本文所述对大家的Go语言程序设计有所帮助。