From fcbee25fa0ebb1d01ad0a4afa6825d992f0085cb Mon Sep 17 00:00:00 2001 From: null31 Date: Tue, 24 Sep 2024 23:17:38 +0200 Subject: [PATCH] Moved GeoIP module to utils package --- utils/geoip.go | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 utils/geoip.go diff --git a/utils/geoip.go b/utils/geoip.go new file mode 100644 index 0000000..903f212 --- /dev/null +++ b/utils/geoip.go @@ -0,0 +1,81 @@ +package utils + +import ( + "net" + "fmt" + + "github.com/oschwald/geoip2-golang" +) + +func HandleGeoIPCommand(ipAddress string, dbCity string, dbASN string) (string, error) { + ip := net.ParseIP(ipAddress) + + // Check if IP/Hostname is valid + if ip == nil { + resolvedIP, err := net.LookupIP(ipAddress) + if err != nil || len(resolvedIP) == 0 { + return "", fmt.Errorf("Invalid IP or hostname: %s", ipAddress) + } + ip = resolvedIP[0] + } + + var ( + city = "N/A" + state = "N/A" + country = "N/A" + asn = "N/A" + isp = "N/A" + ) + + // Lookup City, State and Country info + if cityDb, err := geoip2.Open(dbCity); err == nil { + defer cityDb.Close() + + if cityRecord, err := cityDb.City(ip); err == nil { + if name := cityRecord.City.Names["en"]; name != "" { + city = name + } + + if len(cityRecord.Subdivisions) > 0 { + if name := cityRecord.Subdivisions[0].Names["en"]; name != "" { + state = name + } + } + + if name := cityRecord.Country.Names["en"]; name != "" { + country = name + } + } else { + return "", fmt.Errorf("City Lookup error: %v", err) + } + } else { + return "", fmt.Errorf("Error opening City database: %v", err) + } + + // Lookup ASN info + if asnDb, err := geoip2.Open(dbASN); err == nil { + defer asnDb.Close() + + if asnRecord, err := asnDb.ASN(ip); err == nil { + if asnNum := asnRecord.AutonomousSystemNumber; asnNum != 0 { + asn = fmt.Sprintf("%d", asnNum) + } + + if org := asnRecord.AutonomousSystemOrganization; org != "" { + isp = org + } + } else { + return "", fmt.Errorf("ASN lookup error: %v", err) + } + } else { + return "", fmt.Errorf("Error opening ASN database: %v", err) + } + + // Format the response + response := fmt.Sprintf( + "IP: %s | Location: %s, %s, %s | ASN: %s | ISP: %s", + ip.String(), city, state, country, asn, isp, + ) + + return response, nil +}