Using asnmap as a Library
Beyond its command-line capabilities, asnmap is also designed to be used as a library within your own Go projects. This allows you to programmatically access ASN data and integrate it into your custom tools and workflows.
Note: Before using the library, ensure that a valid ProjectDiscovery Cloud Platform (PDCP) API key is available as an environment variable (PDCP_API_KEY). Refer to the Authentication Guide.
Example Usage
The following example demonstrates the fundamental steps to use the asnmap library: initializing a client, resolving domains, querying data, and processing the results.
This code is adapted from the official example at examples/simple.go.
package main
import (
"encoding/json"
"log"
asnmap "github.com/projectdiscovery/asnmap/libs"
)
func main() {
// 1. Create a new asnmap client
client, err := asnmap.NewClient()
if err != nil {
log.Fatal(err)
}
// 2. Define a list of inputs (ASN, IP, or Organization)
items := []string{
// Query based on ASN ID
"14421",
// Query based on IP
"210.10.122.10",
// Query based on Organization
"pplinknet",
}
// 3. Iterate and query for each item
for _, item := range items {
handleInput(client, item)
}
// 4. Handle domain input separately
domain := "hackerone.com"
// First, resolve the domain to IP addresses
resolvedIps, err := asnmap.ResolveDomain(domain)
if err != nil {
log.Fatal(err)
}
// Then, query for each resolved IP
for _, ip := range resolvedIps {
handleInput(client, ip)
}
}
// handleInput queries the API and processes the response
func handleInput(client *asnmap.Client, item string) {
// GetData performs the API call
responses, err := client.GetData(item)
if err != nil {
log.Fatal(err)
}
// Map the raw API response to a structured Result type
results, err := asnmap.MapToResults(responses)
if err != nil {
log.Fatal(err)
}
// Marshal the results to JSON for display
output, err := json.Marshal(results)
if err != nil {
log.Fatal(err)
}
if len(output) > 0 {
log.Printf("%s: %s\n", item, string(output))
}
}
Key Functions
-
asnmap.NewClient(): Initializes and returns a new client for making requests to the ASN API. It's the first step before any query. -
asnmap.ResolveDomain(domain): A helper function that takes a domain name and returns a slice of its resolved IPv4 and IPv6 addresses. This is necessary because the API queries by IP, not directly by domain. -
client.GetData(item): The core function for fetching data. It accepts a single stringitemwhich can be an ASN ID, an IP address, or an organization name. -
asnmap.MapToResults(responses): Converts the raw API response (a slice of*asnmap.Response) into a more user-friendly format (a slice of*asnmap.Result), which includes CIDR ranges and timestamps.