How to Find GeoIP from an IP?

There are two components of getting detailed info about an IP.

  • A GeoIP database
  • A library to look up the DB

These DBs are not free and have a proprietary format. So a library is required to perform lookups.
One such format is MaxMind and used by GeoIP2 & GeoLite2 DBs.

More @ https://github.com/oschwald/maxminddb-golang

A test program to get detailed IP information

$ cat mytest.go                                                                                                                                          [18:46:01]
//package maxminddb_test
package main

import (
        "fmt"
        "log"
        "net"

        "github.com/oschwald/maxminddb-golang"
)

// This example shows how to decode to a struct
func ExampleReader_Lookup_struct() {
        db, err := maxminddb.Open("./tests/static/GeoIP2-City.mmdb")
        if err != nil {
                log.Fatal(err)
        }
        defer db.Close()

        ip := net.ParseIP("81.2.69.142")

        var record interface{}
        err = db.Lookup(ip, &record)
        if err != nil {
                log.Fatal(err)
        }
        fmt.Print(record)
}

func main() {
        ExampleReader_Lookup_struct()
}

Note that the lookup assumes an interface type. The reason is that the API allows the application to specify what fields to lookup.

You can decide on the record structure after dumping the complete info and picking what you need.

References

Written with StackEdit.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.