Go语言RPC Authorization进行简单ip安全验证的方法
程序员文章站
2023-02-16 22:24:36
本文实例讲述了go语言rpc authorization进行简单ip安全验证的方法。分享给大家供大家参考。具体分析如下:
前言:写网络服务,总要考虑安全机制,对ip和网段...
本文实例讲述了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语言程序设计有所帮助。