/
ip_whois.go
68 lines (60 loc) · 1.3 KB
/
ip_whois.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package dbtools
import (
"fmt"
"math/big"
"net"
"strings"
"github.com/sjlleo/nexttrace-backend/ipgeo"
)
type Ip_whois struct {
Id uint
Begin int64
End int64
Netname string
Owner string
Country_code string
}
func InetNtoA(ip uint64) string {
return fmt.Sprintf("%d.%d.%d.%d",
byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}
func InetAtoN(ip string) int64 {
ret := big.NewInt(0)
ret.SetBytes(net.ParseIP(ip).To4())
return ret.Int64()
}
func SearchIPWhois(ip string) (*Ip_whois, error) {
db := GetDB()
w := Ip_whois{}
ipInt := InetAtoN(ip)
res := db.Where("begin <= ? and end >= ?", ipInt, ipInt).Last(&w)
return &w, res.Error
}
func ParseIPRange(inet string) (int64, int64) {
arr := strings.Split(inet, " - ")
ccd := arr[0]
fmt.Println(ccd)
return InetAtoN(arr[0]), InetAtoN(arr[1])
}
func AddIPWhois(data *ipgeo.IpWhois) error {
db := GetDB()
if data.Netname != "IANA-BLOCK" {
b, e := ParseIPRange(data.Inetnum)
w := Ip_whois{
Begin: b,
End: e,
Netname: data.Netname,
Owner: data.Owner,
Country_code: data.Country_code,
}
res := db.Create(&w)
return res.Error
} else {
w := Ip_whois{
Begin: InetAtoN(data.IP),
End: InetAtoN(data.IP),
}
res := db.Create(&w)
return res.Error
}
}