IP Dabatase

IP Dabatase

IP Dabatase

目前有一些是在线的,有一些是离线的ip地址库

在线

ipip.net ip.sb ip.info等等

几种场景

希望用到logstash的geoip-filter模块,但是只有txt文件

txt2mmdb

go版本 qqzeng to mmdb 仅供参考 部分参考网络

  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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"net"
	"os"
	"strconv"
	"strings"

	"github.com/maxmind/mmdbwriter"
	"github.com/maxmind/mmdbwriter/inserter"
	"github.com/maxmind/mmdbwriter/mmdbtype"
)

func IPv4NumToCidr(ipStartUint32 uint32, ipEndUint32 uint32) (cidrs []string, err error) {
	cidr2mask := []uint32{
		0x00000000, 0x80000000, 0xC0000000,
		0xE0000000, 0xF0000000, 0xF8000000,
		0xFC000000, 0xFE000000, 0xFF000000,
		0xFF800000, 0xFFC00000, 0xFFE00000,
		0xFFF00000, 0xFFF80000, 0xFFFC0000,
		0xFFFE0000, 0xFFFF0000, 0xFFFF8000,
		0xFFFFC000, 0xFFFFE000, 0xFFFFF000,
		0xFFFFF800, 0xFFFFFC00, 0xFFFFFE00,
		0xFFFFFF00, 0xFFFFFF80, 0xFFFFFFC0,
		0xFFFFFFE0, 0xFFFFFFF0, 0xFFFFFFF8,
		0xFFFFFFFC, 0xFFFFFFFE, 0xFFFFFFFF,
	}

	for ipEndUint32 >= ipStartUint32 {
		maxSize := 32
		for maxSize > 0 {

			maskedBase := ipStartUint32 & cidr2mask[maxSize-1]

			if maskedBase != ipStartUint32 {
				break
			}
			maxSize--

		}

		x := math.Log(float64(ipEndUint32-ipStartUint32+1)) / math.Log(2)
		maxDiff := 32 - int(math.Floor(x))
		if maxSize < maxDiff {
			maxSize = maxDiff
		}

		cidrs = append(cidrs, uInt32ToIPv4(ipStartUint32)+"/"+strconv.Itoa(maxSize))

		ipStartUint32 += uint32(math.Exp2(float64(32 - maxSize)))
	}

	return cidrs, err
}

//Convert uint32 to IP
func uInt32ToIPv4(iPuInt32 uint32) (iP string) {
	iP = fmt.Sprintf("%d.%d.%d.%d",
		iPuInt32>>24,
		(iPuInt32&0x00FFFFFF)>>16,
		(iPuInt32&0x0000FFFF)>>8,
		iPuInt32&0x000000FF)
	return iP
}

func main() {
	// read the txt
	f, err := os.Open("./test.txt")
	if err != nil {
		fmt.Println("open file test.txt error " + err.Error())
	}
	defer f.Close()

	writer, _ := mmdbwriter.New(
		mmdbwriter.Options{
			DatabaseType:            "GeoLite2-City",
			RecordSize:              28,
			IncludeReservedNetworks: true,
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	scanner := bufio.NewScanner(f)
	fh, err := os.Create("./test.mmdb")
	fmt.Println("create load mmdb")

	for scanner.Scan() {
		if err != nil {
			fmt.Println("open file test.mmdb error " + err.Error())
		}
		line := scanner.Text()
		ip_array := strings.Split(line, "|")
		fmt.Println(ip_array)
		ip_start_string := ip_array[0]
		ip_end_string := ip_array[1]
		fmt.Println(ip_start_string, ip_end_string)
		ip_start, _ := strconv.Atoi(ip_array[2])
		ip_start_num := uint32(ip_start)
		fmt.Println("ip start num ", ip_start_num)
		ip_end, _ := strconv.Atoi(ip_array[3])
		ip_end_num := uint32(ip_end)
		fmt.Println("ip end num ", ip_end_num)
		continent := ip_array[4]
		fmt.Println("continent :", continent)
		country := ip_array[5]
		fmt.Println("country ", country)
		province := ip_array[6]
		fmt.Println("province ", province)
		city := ip_array[7]
		district := ip_array[8]
		fmt.Println("district ", district)
		isp := ip_array[9]
		fmt.Println("isp ", isp)
		fmt.Println(ip_array[13], ip_array[14])
		lot, _ := strconv.ParseFloat(ip_array[13], 32)
		fmt.Println("longitude ", lot)
		lat, _ := strconv.ParseFloat(ip_array[14], 32)
		fmt.Println("langitude ", lat)

		cidrs, _ := IPv4NumToCidr(ip_start_num, ip_end_num)
		fmt.Println(cidrs)
		for _, cidr := range cidrs {

			fmt.Println("cidr ", cidr)
			_, network, err := net.ParseCIDR(cidr)
			if err != nil {
				fmt.Printf("parse cidr caught error %s", err.Error())
			}
			record := mmdbtype.Map{
				"location": mmdbtype.Map{
					"latitude":  mmdbtype.Uint32(lat),
					"longitude": mmdbtype.Uint32(lot),
					"time_zone": mmdbtype.String(province),
				},
				"city": mmdbtype.Map{
					"names": mmdbtype.Map{
						"en": mmdbtype.String(city),
					},
				},
				"continent": mmdbtype.Map{
					"code": mmdbtype.String(continent),
					"names": mmdbtype.Map{
						"en": mmdbtype.String(continent),
					},
				},
				"country": mmdbtype.Map{
					"names": mmdbtype.Map{
						"en": mmdbtype.String(country),
					},
					"iso_code": mmdbtype.String(isp),
				},
			}
			if err := writer.InsertFunc(network, inserter.TopLevelMergeWith(record)); err != nil {
				log.Fatal(err)
			}
		}
	}

	_, err = writer.WriteTo(fh)
	if err != nil {
		log.Fatal(err)
	}
	defer fh.Close()
}
  • 这里面有几个坑 write要放到后面
  • 原来的geoip-filter模块我无法放到对应的region字段,感兴趣的可以深挖下源码
自己测试
  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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
➜  geoip-go mmdblookup --file /tmp/GeoLite2-City.mmdb --ip 65.158.50.108 

  {
    "city": 
      {
        "geoname_id": 
          4482084 <uint32>
        "names": 
          {
            "en": 
              "Newport" <utf8_string>
            "ru": 
              "Ньюпорт" <utf8_string>
          }
      }
    "continent": 
      {
        "code": 
          "NA" <utf8_string>
        "geoname_id": 
          6255149 <uint32>
        "names": 
          {
            "de": 
              "Nordamerika" <utf8_string>
            "en": 
              "North America" <utf8_string>
            "es": 
              "Norteamérica" <utf8_string>
            "fr": 
              "Amérique du Nord" <utf8_string>
            "ja": 
              "北アメリカ" <utf8_string>
            "pt-BR": 
              "América do Norte" <utf8_string>
            "ru": 
              "Северная Америка" <utf8_string>
            "zh-CN": 
              "北美洲" <utf8_string>
          }
      }
    "country": 
      {
        "geoname_id": 
          6252001 <uint32>
        "iso_code": 
          "US" <utf8_string>
        "names": 
          {
            "de": 
              "USA" <utf8_string>
            "en": 
              "United States" <utf8_string>
            "es": 
              "Estados Unidos" <utf8_string>
            "fr": 
              "États-Unis" <utf8_string>
            "ja": 
              "アメリカ合衆国" <utf8_string>
            "pt-BR": 
              "Estados Unidos" <utf8_string>
            "ru": 
              "США" <utf8_string>
            "zh-CN": 
              "美国" <utf8_string>
          }
      }
    "location": 
      {
        "accuracy_radius": 
          200 <uint16>
        "latitude": 
          34.755100 <double>
        "longitude": 
          -76.906900 <double>
        "metro_code": 
          545 <uint16>
        "time_zone": 
          "America/New_York" <utf8_string>
      }
    "postal": 
      {
        "code": 
          "28570" <utf8_string>
      }
    "registered_country": 
      {
        "geoname_id": 
          6252001 <uint32>
        "iso_code": 
          "US" <utf8_string>
        "names": 
          {
            "de": 
              "USA" <utf8_string>
            "en": 
              "United States" <utf8_string>
            "es": 
              "Estados Unidos" <utf8_string>
            "fr": 
              "États-Unis" <utf8_string>
            "ja": 
              "アメリカ合衆国" <utf8_string>
            "pt-BR": 
              "Estados Unidos" <utf8_string>
            "ru": 
              "США" <utf8_string>
            "zh-CN": 
              "美国" <utf8_string>
          }
      }
    "subdivisions": 
      [
        {
          "geoname_id": 
            4482348 <uint32>
          "iso_code": 
            "NC" <utf8_string>
          "names": 
            {
              "en": 
                "North Carolina" <utf8_string>
              "es": 
                "Carolina del Norte" <utf8_string>
              "fr": 
                "Caroline du Nord" <utf8_string>
              "ja": 
                "ノースカロライナ州" <utf8_string>
              "pt-BR": 
                "Carolina do Norte" <utf8_string>
              "ru": 
                "Северная Каролина" <utf8_string>
              "zh-CN": 
                "北卡罗来纳州" <utf8_string>
            }
        }
      ]
  }
logstash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
cat test.conf
input {
   stdin {}
}

filter {
  geoip {
    source => "message"
    target => "geoip"
    database => "/data/geoip/test.mmdb"
  }
}

output {
  stdout { codec => rubydebug } 
}

希望用到logstash里面,只有专有db格式的

需要放到nginx里面的

建议用nginx自带的geoip模块或者用ipdb的模块

参考文档