package utils import ( "encoding/hex" "errors" "fmt" "ipv6-test-node/internal/pkg/protocol" "net" "strings" ) func GetIPVersion(ip net.IP) (protocol.IPVersion, error) { if ip == nil { return 0, errors.New("invalid IP address") } if ip.To4() != nil { return protocol.IPv4, nil } else if ip.To16() != nil { return protocol.IPv6, nil } else { return 0, errors.New("invalid IP address") } } func GetASN(ip protocol.IP) (string, error) { var query string if ip.Version == 4 { query = fmt.Sprintf("%sorigin.asn.cymru.com", reverseIPv4(ip.Address)) } else if ip.Version == 6 { query = fmt.Sprintf("%sorigin6.asn.cymru.com", reverseIPv6(ip.Address)) } txtRecords, err := net.LookupTXT(query) if err != nil { return "", err } if len(txtRecords) > 0 { parts := strings.Split(txtRecords[0], " | ") if len(parts) > 0 { return "AS" + parts[0], nil } } return "", fmt.Errorf("ASN not found") } func GetISPName(asn string) (string, error) { query := fmt.Sprintf("%s.asn.cymru.com", asn) txtRecords, err := net.LookupTXT(query) if err != nil { return "", err } if len(txtRecords) > 0 { parts := strings.Split(txtRecords[0], " | ") if len(parts) > 0 { return parts[4], nil } } return "", fmt.Errorf("ISP not found") } func ToIP(address net.IP) protocol.IP { version, err := GetIPVersion(address) if err != nil { return protocol.IP{} } return protocol.IP{Address: address, Version: version} } func reverseIPv4(ip net.IP) string { return fmt.Sprintf("%d.%d.%d.%d.", ip[3], ip[2], ip[1], ip[0]) } func reverseIPv6(ip net.IP) string { var dst []byte dst = make([]byte, hex.EncodedLen(len(ip))) hex.Encode(dst, ip) var reversed string for i := len(dst) - 1; i >= 0; i-- { reversed = reversed + string(dst[i]) + "." } return reversed }