The example in this article describes the approach of the Go Language RPC authorization for simple IP Security authentication. Share to everyone for your reference. The specific analysis is as follows:
Write Network service, always consider security mechanism, the IP and network segment to judge is the simplest authentication mechanism. Then want to do a similar registration of security authentication mechanism, can reduce the trouble of the configuration file, but also can be a good security management.
Directly on the code:
Copy Code code as follows:
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 will help you with your go language program.