Practical IP-Level Unsupervised Classification Using HDBSCAN and K-Means
From the publisher’s feed, collected in the ZeroLabs newsroom.
A recurring challenge in network analytics arises when two distinct consumer brands are operated by the same legal entity and share a single Autonomous System Number (ASN). Standard IP-to-ISP databases resolve every IP in that ASN to one company name, making it impossible to distinguish which brand a given measurement session belongs to. No labelled training set exists.The input is two datasets (IPv4 and IPv6) where each row represents aggregated sessions sharing the same DNS resolver IP, with accompanying fields: IP range bounds, ASN organisation string, geographic region, connection public IP, and a session count. The objective is to assign each row a brand label using only these network-layer signals.Photo by BoliviaInteligente on Unsplash1. Data Structure and Signal SourcesEach row represents one or more device sessions grouped by their configured DNS resolver address. The key fields are:ip_lower_str / ip_upper_str — lower and upper bounds of the IP range; block rows contain wildcard placeholders (e.g. 118.x.x.x)QOS_DNSAddresses — the DNS resolver IP from the device; for home broadband users, this is typically the CPE router’s own IP, not a public upstream resolver.AsnOrganization / isp — ASN-derived organisation strings from a third-party IP database.OneSource_PublicIp — the connection IP observed by the measurement server.Location_Region — geographic region label.numrecords — count of sessions aggregated into this row.The central insight is that the DNS resolver IP is often the home router’s own address rather than a public upstream resolver like 8.8.8.8 or 1.1.1.1. This means the DNS IP encodes information about the CPE hardware and sub-network allocated by the ISP — a signal that is entirely invisible to standard ASN lookups.2. Feature Engineering2.1 Wildcard IP CleaningBlock IP ranges use x as a wildcard placeholder in lower-order octets. Before any numeric processing, these are normalised to concrete addresses by substituting 0:clean = lambda s: re.sub(r'\b[xX]\b', '0', str(s).strip())2.2 Prefix ExtractionRather than treating IP addresses as opaque strings, the first two octets (IPv4) or first two 16-bit hextets (IPv6) are extracted as compact categorical features. This collapses the address space to a manageable prefix set while preserving the sub-network signal:# IPv4 dns_prefix = '.'.join(ip_str.split('.')[:2]) # e.g. '118.238' # IPv6 - extract first two hextets from packed bytes packed = ipaddress.IPv6Address(ip_str).packed h1 = (packed[0] For IPv6, the second hextet (h2) emerged during EDA as the primary discriminating feature — different sub-network allocations within the same /20 block correspond to different product lines served by the same parent organisation.2.3 Log Transformation of Skewed NumericsTwo features spanned several orders of magnitude: IP range size (from 256 addresses for a /24 up to 2⁹⁶ for a large IPv6 allocation) and numrecords (session counts from tens to millions). Without transformation, raw differences of this scale would dominate Euclidean distance in clustering. Log transformation compresses the distribution:log_range = math.log2(ip_upper - ip_lower) if ip_upper > ip_lower else 0 log_records = np.log1p(numrecords)Note the use of math.log2() rather than np.log2() for IPv6 range sizes. IPv6 address arithmetic produces Python arbitrary-precision integers, which NumPy cannot process natively — np.log2() raises AttributeError: ‘int’ object has no attribute ‘log2’ on these values. Staying in pure Python before passing to NumPy is required.2.4 Frequency Encoding of CategoricalsCategorical fields (AsnOrganization, isp, region) are encoded by replacing each category with its frequency count in the dataset. This is preferred over one-hot encoding because the cardinality is high (hundreds of distinct ASNs) and frequency itself is a meaningful signal — rare networks are more distinctive than common ones:freq_map = df['AsnOrganization'].value_counts().to_dict() df['asn_freq'] = df['AsnOrganization'].map(freq_map)2.5 StandardisationAll numeric features are passed through StandardScaler (zero mean, unit variance) before clustering. This ensures no single feature dominates the Euclidean distance metric regardless of its original numeric range.3. Clustering ExplorationK-Means and DBSCAN are fundamental clustering algorithms that diverge sharply in their underlying mechanics and applications. K-Means is a centroid-based method that partitions data into a pre-specified number (k) of spherical clusters by minimizing within-cluster distances, making it computationally efficient but highly sensitive to outliers and assuming the clusters are spherical.In contrast, DBSCAN is a density-based algorithm that does not require the user to define the number of clusters; instead, it groups densely packed points based on a distance epsilon (ε) and a minimum point threshold (MinPts), allowing it to discover arbitrarily shaped clusters while robustly labeling sparse points as noise. Consequently, their main differences lie in cluster shape assumptions (spherical vs. arbitrary), the necessity of a predefined cluster count, and their handling of outliers, though DBSCAN’s performance is heavily dependent on proper parameter tuning and can struggle when densities vary significantly across the dataset.3.1 K-Means (baseline)K-Means with k=3 served as a quick baseline to understand the rough structure of the feature space. It confirmed that the data separates into broadly different network types but was otherwise inadequate: its assumption of spherical, equally-sized clusters produced arbitrary boundaries across the irregular density structure in the data.3.2 DBSCANDBSCAN (Density-Based Spatial Clustering of Applications with Noise) was applied next. Its key advantage is producing a noise class (label -1) for points that don’t fit any dense region — useful for flagging outlier rows linked to anomalous ASNs. The limitation is that a single global eps parameter is poorly suited to datasets with clusters of varying density.3.3 HDBSCAN (final choice)HDBSCAN (Hierarchical DBSCAN) fundamentally improves upon DBSCAN by overcoming its most critical limitation: the reliance on a single, globally applied density threshold (epsilon). Instead of forcing a one-size-fits-all parameter, HDBSCAN constructs a hierarchy of clusters across all possible density scales and uses a stability-based metric to extract the most persistent clusters. This key advantage allows it to automatically discover clusters of widely varying densities within the same dataset — a scenario where traditional DBSCAN inevitably fails — while simultaneously eliminating the need for manual tuning of epsilon. Additionally, its advanced pruning mechanism provides more intelligent noise classification, often yielding more meaningful and granular cluster structures without sacrificing the robustness that makes density-based clustering so valuable for complex, real-world data.clusterer = hdbscan.HDBSCAN( min_cluster_size=120, # minimum points to form a cluster min_samples=5, # controls conservativeness of noise labelling metric='euclidean', core_dist_n_jobs=-1, # parallelise core distance computation prediction_data=True # enables soft cluster assignment ) labels = clusterer.fit_predict(X_scaled)HDBSCAN produced stable, interpretable clusters and correctly isolated anomalous sub-networks as noise rather than forcing them into existing clusters — a behaviour neither K-Means nor DBSCAN reliably achieved.4. Label Assignment via Reverse DNS (PTR) Lookups4.1 What is PTR?A PTR (Pointer) record, commonly known as reverse DNS, serves as the exact counterpart to the more familiar forward DNS lookup by mapping an IP address back to a fully qualified domain name (FQDN).While forward DNS translates human-readable names into numerical IPs, reverse DNS performs the inverse query — taking a numerical address and resolving it to a hostname — which is essential for a variety of operational and security tasks. Its most prominent application lies in email delivery, where receiving mail servers perform reverse DNS lookups on incoming sender IPs as a primary anti-spam measure, often rejecting messages from addresses that lack a valid, matching PTR record.Beyond email, PTR records are invaluable for network troubleshooting (e.g., tracing routes, deciphering server logs), security forensics, and authenticating access in systems like FTP or SSH, where knowing the reverse hostname of a connecting client adds a crucial layer of identity verification and auditability.4.2 RationaleWith clusters established, the next step is assigning brand labels. Home routers often register PTR records (reverse DNS) with hostnames that include manufacturer or service identifiers. Because the DNS resolver IP is the router’s own address for many home users, resolving it via PTR can act as a hardware fingerprint.4.3 Async Resolution with dnspythonPTR resolution is implemented with asyncio and dnspython, with a semaphore controlling concurrency and retry logic with exponential backoff across multiple upstream resolvers:async def resolve_one(ip: str) -> str: try: rev = dns.reversename.from_address(ip) ans = await resolver.resolve(rev, 'PTR') return str(ans[0]).rstrip('.') except Exception: return '' # NXDOMAIN or timeout → no PTR record5. From Cluster Patterns to a Production Rule ClassifierOnce PTR resolution exposed distinguishing patterns — specific sub-prefix ranges and public IP ranges associated with each brand — the clustering step became unnecessary at inference time. The production classifier is a pure rule lookup: faster, deterministic, and fully interpretable.This illustrates a general lifecycle: clustering and PTR lookups serve as a discovery and annotation engine during development; the rules they expose are hardened into a lightweight classifier that runs without any ML dependencies.6. Multi-Signal FusionNo single signal covered all rows. The final classifier combines four independent signals evaluated in priority order, falling through to the next when the previous is inconclusive.Signal 1 — DNS sub-prefix (IPv6)The second hextet of the DNS IPv6 address maps directly to a brand sub-allocation within the shared /20 block.Signal 2 — DNS prefix + public IP prefix (IPv4)Combining the DNS /16 prefix with the connection public IP /16 prefix disambiguates brand at the IPv4 level.Signal 3 — Geographic coverage mapAn external coverage table (brand availability by prefecture) acts as a tiebreaker for ambiguous rows. Regions where Brand A has 0% coverage are definitively Brand B; regions with 100% Brand A coverage are definitively Brand A. Partial-coverage regions remain ambiguous.Signal 4 — Wi-Fi router manufacturer (OUI)The MAC OUI of the access point the device is connected to reveals the CPE hardware brand. Certain router manufacturers supply equipment exclusively to one service, providing a signal entirely orthogonal to the IP layer and effective even when IP-based signals are unavailable.7. Lessons LearnedClustering is an annotation engine, not the final product. Its value is surfacing the rules it helps you discover; those rules then replace the model entirely at inference time.PTR records are underutilised in network analytics. When the DNS resolver IP is the home router rather than a public upstream resolver, reverse DNS becomes a hardware fingerprint.math.log2() vs np.log2() is a silent footgun at 128-bit integer scale. Any feature involving IPv6 address arithmetic must remain in pure Python before entering NumPy pipelines.Multi-signal fusion with an explicit priority chain is more maintainable than a single model attempting to learn all signals jointly. Each signal can be validated, updated, or disabled independently.The absence of ground truth is not a blocker. Clustering + PTR provides a reliable annotation path; the key is sampling strategically rather than exhaustively.Practical IP-Level Unsupervised Classification Using HDBSCAN and K-Means was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.