-
Notifications
You must be signed in to change notification settings - Fork 4
/
ip.go
76 lines (67 loc) · 2.39 KB
/
ip.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
69
70
71
72
73
74
75
76
package geo
import (
"errors"
"net"
"github.com/oschwald/geoip2-golang"
)
// IPInfo represents IP address information from Maxmind's GeoLite2 database
type IPInfo struct {
IP string `json:"ip"`
IsAnonymousProxy bool `json:"is_anonymous_proxy"`
IsSatelliteProvider bool `json:"is_satellite_provider"`
City string `json:"city"`
ContinentName string `json:"continent_name"`
ContinentCode string `json:"continent_code"`
IsInEuropeanUnion bool `json:"is_in_european_union"`
CountryName string `json:"country_name"`
CountryCode string `json:"country_code"`
TimeZone string `json:"timezone"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
AccuracyRadius uint16 `json:"accuracy_radius"`
ASNOrg string `json:"asn_org"`
ASN uint `json:"asn"`
}
// Info returns GeoIP information from given IP address
func Info(ipAddr string) (*IPInfo, error) {
ip := net.ParseIP(ipAddr)
if ip == nil {
return nil, errors.New("Invalid IP address")
}
dbCity, err := geoip2.Open("./assets/geoip/GeoLite2-City.mmdb")
if err != nil {
return nil, errors.New("Cannot open GeoIP City database")
}
defer dbCity.Close()
dbAsn, err := geoip2.Open("./assets/geoip/GeoLite2-ASN.mmdb")
if err != nil {
return nil, errors.New("Cannot open GeoIP ASN database")
}
defer dbAsn.Close()
city, err := dbCity.City(ip)
if err != nil {
return nil, errors.New("Cannot read GeoIP City database")
}
asn, err := dbAsn.ASN(ip)
if err != nil {
return nil, errors.New("Cannot read GeoIP ASN database")
}
qip := IPInfo{
IP: ipAddr,
IsAnonymousProxy: city.Traits.IsAnonymousProxy,
IsSatelliteProvider: city.Traits.IsSatelliteProvider,
City: city.City.Names["en"],
ContinentName: city.Continent.Names["en"],
ContinentCode: city.Continent.Code,
IsInEuropeanUnion: city.Country.IsInEuropeanUnion,
CountryName: city.Country.Names["en"],
CountryCode: city.Country.IsoCode,
TimeZone: city.Location.TimeZone,
Latitude: city.Location.Latitude,
Longitude: city.Location.Longitude,
AccuracyRadius: city.Location.AccuracyRadius,
ASNOrg: asn.AutonomousSystemOrganization,
ASN: asn.AutonomousSystemNumber,
}
return &qip, nil
}