Grok got it working cross-platform (tested on Windows and Linux) without Bonjour, DNS-SD, etc., by using python-zeroconf, installed using pip install zeroconf.
matter-map-cross-platform-pip-zeroconf.py
#!/usr/bin/env python3
"""
matter-map for cross-platform, tested on Windows and Linux.
Requires:
pip install zeroconf
smartthings CLI in PATH
"""
import ipaddress
import json
import sys
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from zeroconf import IPVersion, ServiceBrowser, Zeroconf
# ---------------- configuration ----------------
CACHE_TTL = 300 # seconds for hostname cache
MAX_THREADS = 10 # max parallel DNS resolution threads
BROWSE_TIMEOUT = 15 # max seconds to browse for _matter._tcp
BROWSE_QUIET = 2.5 # stop early once this long passes with no new service
# Matter operational ads (especially Thread) arrive on IPv6. Zeroconf's
# default is IPv4-only, which sees none of them on this network.
# ---------------- helpers ----------------
def run(cmd):
import subprocess
return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)
def get_locations():
locations = json.loads(run(["smartthings", "locations", "-j"]))
id_to_name = {}
name_to_id = {}
for loc in locations:
id_to_name[loc["locationId"]] = loc["name"]
name_to_id[loc["name"]] = loc["locationId"]
return id_to_name, name_to_id
def get_matter_devices(location_id=None):
cmd = ["smartthings", "devices", "--type", "MATTER", "-j"]
if location_id:
cmd += ["--location", location_id]
devices = json.loads(run(cmd))
results = []
for d in devices:
network_id = d.get("matter", {}).get("networkId")
if not network_id:
continue
results.append({
"label": d.get("label", "UNKNOWN"),
"instance": network_id,
"locationId": d.get("locationId"),
"hostname": "", # will be filled by DNS
"ipv4": "",
"ipv6": "",
})
return results
# ---------------- mDNS via zeroconf (no Bonjour) ----------------
def _instance_from_service_name(name):
"""CC55...-DB25...._matter._tcp.local. -> CC55...-DB25..."""
suffix = "._matter._tcp.local."
if name.endswith(suffix):
return name[: -len(suffix)]
return name.split("._matter._tcp.")[0]
def _pick_addresses(addr_strings):
"""Choose one IPv4 and one IPv6, matching what dns-sd tends to surface.
Prefer a global IPv6 address, then a unique-local (Thread) address, then
link-local. info.addresses is often IPv4-only even when AAAA records were
received; callers should pass ServiceInfo.parsed_addresses().
"""
ipv4 = ""
v6_global = []
v6_ula = []
v6_link = []
for raw in addr_strings:
try:
ip = ipaddress.ip_address(raw.split("%", 1)[0])
except ValueError:
continue
if ip.version == 4:
if not ipv4:
ipv4 = str(ip)
elif ip.is_link_local:
v6_link.append(ip)
elif ip.is_private:
v6_ula.append(ip)
else:
v6_global.append(ip)
chosen = (v6_global or v6_ula or v6_link or [None])[0]
ipv6 = chosen.compressed if chosen is not None else ""
return ipv4, ipv6
def get_dns_sd_data(debug_dns=False):
"""Discover _matter._tcp services using pure-Python zeroconf."""
data = defaultdict(dict)
names = []
last_add = time.time()
class Listener:
def add_service(self, zc, type_, name):
nonlocal last_add
if debug_dns:
print(f"[DEBUG] Found: {name}")
if name not in names:
names.append(name)
last_add = time.time()
def remove_service(self, zc, type_, name):
pass
def update_service(self, zc, type_, name):
pass
# Do not resolve inside the listener: get_service_info takes the zeroconf
# lock and deadlocks if called from a ServiceBrowser callback.
# A fixed short sleep drops Thread devices when the first query is late.
zc = Zeroconf(ip_version=IPVersion.All)
browser = ServiceBrowser(zc, "_matter._tcp.local.", Listener())
if debug_dns:
print(f"[DEBUG] Browsing _matter._tcp for up to {BROWSE_TIMEOUT}s...")
started = time.time()
while time.time() - started < BROWSE_TIMEOUT:
time.sleep(0.25)
if names and time.time() - last_add >= BROWSE_QUIET:
break
if debug_dns:
print(f"[DEBUG] Browse saw {len(names)} services")
for name in names:
info = zc.get_service_info("_matter._tcp.local.", name, timeout=3000)
if not info:
if debug_dns:
print(f"[DEBUG] No service info for {name}")
continue
instance = _instance_from_service_name(name)
hostname = info.server.rstrip(".") if info.server else ""
data[instance]["hostname"] = hostname
ipv4, ipv6 = _pick_addresses(info.parsed_addresses())
if ipv4:
data[instance]["ipv4"] = ipv4
if ipv6:
data[instance]["ipv6"] = ipv6
if debug_dns:
print(f"[DEBUG] {instance} {hostname} {ipv6} {ipv4}")
browser.cancel()
zc.close()
return data
# ---------------- hostname cache (kept for compatibility) ----------------
hostname_cache = {} # hostname -> (ipv4, ipv6, timestamp)
def resolve_hostname_cached(hostname, debug_dns=False):
"""Fallback resolution if zeroconf didn't already give addresses.
On modern Windows the native resolver often works for .local names
without Bonjour, so we try it first.
"""
now = time.time()
if hostname in hostname_cache:
ipv4, ipv6, ts = hostname_cache[hostname]
if now - ts < CACHE_TTL:
return ipv4, ipv6 # use cached
ipv4, ipv6 = "", ""
try:
import socket
# getaddrinfo works for .local on Windows 10 1703+ without Bonjour
results = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
for res in results:
family, _, _, _, sockaddr = res
ip = sockaddr[0]
if family == socket.AF_INET and not ipv4:
ipv4 = ip
elif family == socket.AF_INET6 and not ipv6:
# skip link-local scope id if present
ipv6 = ip.split("%")[0]
except Exception as e:
if debug_dns:
print(f"[DEBUG] getaddrinfo failed for {hostname}: {e}")
hostname_cache[hostname] = (ipv4, ipv6, now)
return ipv4, ipv6
# ---------------- help ----------------
def print_help():
print("""Usage: matter-map [LOCATION] [OPTIONS]
Positional arguments:
LOCATION Filter devices by location name
Options:
--help Show this help message and exit
--sort=FIELD Sort by field: label, location, instance, hostname, ipv4, ipv6
--reverse Reverse sort order
--debug-dns Print debug info for mDNS queries""")
# ---------------- main ----------------
def main():
sort_key = "label"
reverse = False
location_arg = None
debug_dns = False
args = sys.argv[1:]
positional_args = []
for arg in args:
if arg == "--help":
print_help()
sys.exit(0)
elif arg == "--reverse":
reverse = True
elif arg == "--debug-dns":
debug_dns = True
elif arg.startswith("--sort="):
sort_key = arg.split("=", 1)[1]
elif arg.startswith("-"):
print(f"Unknown option: {arg}", file=sys.stderr)
sys.exit(1)
else:
positional_args.append(arg)
if len(positional_args) > 1:
print("Error: only one location name may be specified", file=sys.stderr)
sys.exit(1)
if positional_args:
location_arg = positional_args[0]
valid_sorts = {"label", "location", "instance", "hostname", "ipv4", "ipv6"}
if sort_key not in valid_sorts:
print(f"Invalid sort key: {sort_key}", file=sys.stderr)
print(f"Valid options: {', '.join(sorted(valid_sorts))}", file=sys.stderr)
sys.exit(1)
id_to_name, name_to_id = get_locations()
location_id = None
if location_arg:
location_id = name_to_id.get(location_arg)
if not location_id:
print("Unknown location", file=sys.stderr)
sys.exit(1)
devices = get_matter_devices(location_id)
dns_data = get_dns_sd_data(debug_dns)
# Merge DNS-SD data into devices
for d in devices:
dns = dns_data.get(d["instance"], {})
d["hostname"] = dns.get("hostname", "UNKNOWN")
d["ipv4"] = dns.get("ipv4", "")
d["ipv6"] = dns.get("ipv6", "")
d["location"] = id_to_name.get(d.get("locationId"), "UNKNOWN")
# Resolve hostnames that mDNS did not already give an address for.
# Windows getaddrinfo can answer .local without Bonjour, but it is slower
# and often returns a different address than the Matter SRV record.
to_resolve = [
d for d in devices
if d["hostname"] not in ("", "UNKNOWN") and not (d["ipv4"] or d["ipv6"])
]
with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
future_to_device = {
executor.submit(resolve_hostname_cached, d["hostname"], debug_dns): d
for d in to_resolve
}
for future in as_completed(future_to_device):
d = future_to_device[future]
try:
ipv4, ipv6 = future.result()
d["ipv4"] = ipv4 or d["ipv4"]
d["ipv6"] = ipv6 or d["ipv6"]
except Exception:
pass
# Sort and group
devices.sort(key=lambda r: r.get(sort_key, ""), reverse=reverse)
grouped = defaultdict(list)
for r in devices:
grouped[r.get("location", "UNKNOWN")].append(r)
# Print output (same format as original)
print(
f"{'DEVICE LABEL':<25} {'LOCATION':<15} {'INSTANCE NAME/NETWORK ID':<40} "
f"{'HOSTNAME':<30} {'IPv6 ADDRESS':<40} {'IPv4 ADDRESS':<20}"
)
print("-" * 180)
for location in sorted(grouped):
for r in grouped[location]:
print(
f"{r['label']:<25} "
f"{location:<15} "
f"{r['instance']:<40} "
f"{r['hostname']:<30} "
f"{r['ipv6']:<40} "
f"{r['ipv4']:<20}"
)
if __name__ == "__main__":
main()
matter-map-windows-built-in.py
#!/usr/bin/env python3
"""
matter-map for Windows — native DNS-SD via ctypes (no Bonjour, no extra packages).
Uses DnsServiceBrowse / DnsServiceResolve from dnsapi.dll.
Browse answers often include SRV, A, and AAAA records for Wi-Fi devices.
Thread devices frequently arrive as PTR only, so those are resolved separately.
Requires Windows 10 1703+ / Windows 11 and the smartthings CLI in PATH.
"""
import ctypes
import ipaddress
import json
import socket
import sys
import threading
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from ctypes import wintypes
# ---------------- Windows DNS-SD bindings ----------------
dnsapi = ctypes.WinDLL("dnsapi")
DNS_QUERY_REQUEST_VERSION1 = 1
DNS_REQUEST_PENDING = 9506
ERROR_CANCELLED = 1223
DNS_TYPE_A = 1
DNS_TYPE_PTR = 12
DNS_TYPE_AAAA = 28
DNS_TYPE_SRV = 33
class DNS_SERVICE_CANCEL(ctypes.Structure):
_fields_ = [("reserved", ctypes.c_void_p)]
class DNS_SERVICE_BROWSE_REQUEST(ctypes.Structure):
_fields_ = [
("Version", wintypes.ULONG),
("InterfaceIndex", wintypes.ULONG),
("QueryName", wintypes.LPCWSTR),
("pBrowseCallback", ctypes.c_void_p),
("pQueryContext", ctypes.c_void_p),
]
class DNS_SERVICE_RESOLVE_REQUEST(ctypes.Structure):
_fields_ = [
("Version", wintypes.ULONG),
("InterfaceIndex", wintypes.ULONG),
("QueryName", wintypes.LPWSTR),
("pResolveCompletionCallback", ctypes.c_void_p),
("pQueryContext", ctypes.c_void_p),
]
class DNS_SERVICE_INSTANCE(ctypes.Structure):
_fields_ = [
("pszInstanceName", wintypes.LPWSTR),
("pszHostName", wintypes.LPWSTR),
("ip4Address", ctypes.POINTER(wintypes.DWORD)),
("ip6Address", ctypes.POINTER(ctypes.c_ubyte * 16)),
("wPort", wintypes.WORD),
("wPriority", wintypes.WORD),
("wWeight", wintypes.WORD),
("dwPropertyCount", wintypes.DWORD),
("keys", ctypes.POINTER(wintypes.LPWSTR)),
("values", ctypes.POINTER(wintypes.LPWSTR)),
("dwInterfaceIndex", wintypes.DWORD),
]
class DNS_RECORD(ctypes.Structure):
pass
# Fixed header is 32 bytes on 64-bit Windows. The Data union starts there.
# pData aliases the first pointer of PTR (pNameHost) and SRV (pNameTarget).
DNS_RECORD._fields_ = [
("pNext", ctypes.POINTER(DNS_RECORD)),
("pName", wintypes.LPWSTR),
("wType", wintypes.WORD),
("wDataLength", wintypes.WORD),
("Flags", wintypes.DWORD),
("dwTtl", wintypes.DWORD),
("dwReserved", wintypes.DWORD),
("pData", wintypes.LPWSTR),
]
BROWSE_CALLBACK = ctypes.WINFUNCTYPE(
None, wintypes.DWORD, ctypes.c_void_p, ctypes.POINTER(DNS_RECORD)
)
RESOLVE_CALLBACK = ctypes.WINFUNCTYPE(
None, wintypes.DWORD, ctypes.c_void_p, ctypes.POINTER(DNS_SERVICE_INSTANCE)
)
dnsapi.DnsServiceBrowse.argtypes = [
ctypes.POINTER(DNS_SERVICE_BROWSE_REQUEST),
ctypes.POINTER(DNS_SERVICE_CANCEL),
]
dnsapi.DnsServiceBrowse.restype = wintypes.DWORD
dnsapi.DnsServiceBrowseCancel.argtypes = [ctypes.POINTER(DNS_SERVICE_CANCEL)]
dnsapi.DnsServiceBrowseCancel.restype = wintypes.DWORD
dnsapi.DnsServiceResolve.argtypes = [
ctypes.POINTER(DNS_SERVICE_RESOLVE_REQUEST),
ctypes.POINTER(DNS_SERVICE_CANCEL),
]
dnsapi.DnsServiceResolve.restype = wintypes.DWORD
dnsapi.DnsServiceResolveCancel.argtypes = [ctypes.POINTER(DNS_SERVICE_CANCEL)]
dnsapi.DnsServiceResolveCancel.restype = wintypes.DWORD
dnsapi.DnsServiceFreeInstance.argtypes = [ctypes.POINTER(DNS_SERVICE_INSTANCE)]
dnsapi.DnsServiceFreeInstance.restype = None
# ---------------- configuration ----------------
CACHE_TTL = 300
MAX_THREADS = 10
BROWSE_TIMEOUT = 15
BROWSE_QUIET = 2.5
RESOLVE_TIMEOUT = 8
# ---------------- helpers ----------------
def run(cmd):
import subprocess
return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)
def get_locations():
locations = json.loads(run(["smartthings", "locations", "-j"]))
id_to_name = {}
name_to_id = {}
for loc in locations:
id_to_name[loc["locationId"]] = loc["name"]
name_to_id[loc["name"]] = loc["locationId"]
return id_to_name, name_to_id
def get_matter_devices(location_id=None):
cmd = ["smartthings", "devices", "--type", "MATTER", "-j"]
if location_id:
cmd += ["--location", location_id]
devices = json.loads(run(cmd))
results = []
for d in devices:
network_id = d.get("matter", {}).get("networkId")
if not network_id:
continue
results.append({
"label": d.get("label", "UNKNOWN"),
"instance": network_id,
"locationId": d.get("locationId"),
"hostname": "",
"ipv4": "",
"ipv6": "",
})
return results
def _instance_from_service_name(name):
suffix = "._matter._tcp.local"
lower = name.lower()
idx = lower.find(suffix)
if idx >= 0:
return name[:idx]
return name.split("._matter._tcp.")[0]
def _record_data(record, size):
return ctypes.string_at(ctypes.addressof(record) + 32, size)
def _pick_addresses(addr_strings):
"""Prefer a global IPv6 address, then unique-local, then link-local."""
ipv4 = ""
v6_global = []
v6_ula = []
v6_link = []
for raw in addr_strings:
try:
ip = ipaddress.ip_address(str(raw).split("%", 1)[0])
except ValueError:
continue
if ip.version == 4:
if not ipv4:
ipv4 = str(ip)
elif ip.is_link_local:
v6_link.append(ip)
elif ip.is_private:
v6_ula.append(ip)
else:
v6_global.append(ip)
chosen = (v6_global or v6_ula or v6_link or [None])[0]
ipv6 = chosen.exploded.upper() if chosen is not None else ""
return ipv4, ipv6
def _format_ipv6(text):
if not text:
return ""
try:
return ipaddress.IPv6Address(text.split("%", 1)[0]).exploded.upper()
except ValueError:
return text
# ---------------- native DNS-SD discovery ----------------
class _ContextBox(ctypes.Structure):
_fields_ = [("obj", ctypes.py_object)]
def _context_from_ptr(context_ptr):
if not context_ptr:
return None
return ctypes.cast(context_ptr, ctypes.POINTER(_ContextBox)).contents.obj
class DiscoveryContext:
def __init__(self):
self.services = {} # instance -> {"hostname", "ipv4": set, "ipv6": set}
self.lock = threading.Lock()
self.last_add = time.time()
self.resolve_done = threading.Event()
self.pending_resolves = 0
def _service(ctx, instance):
entry = ctx.services.get(instance)
if entry is None:
entry = {"hostname": "", "ipv4": set(), "ipv6": set()}
ctx.services[instance] = entry
ctx.last_add = time.time()
return entry
def browse_callback(status, context_ptr, record):
if status not in (0, ERROR_CANCELLED) or not record or not context_ptr:
return
ctx = _context_from_ptr(context_ptr)
if ctx is None:
return
rec = record
current = None
try:
while rec:
item = rec.contents
if item.wType == DNS_TYPE_PTR and item.pData:
current = _instance_from_service_name(ctypes.wstring_at(item.pData))
with ctx.lock:
_service(ctx, current)
elif current and item.wType == DNS_TYPE_SRV and item.pData:
hostname = ctypes.wstring_at(item.pData).rstrip(".")
with ctx.lock:
entry = _service(ctx, current)
if hostname:
entry["hostname"] = hostname
elif current and item.wType == DNS_TYPE_A and item.wDataLength >= 4:
ipv4 = socket.inet_ntoa(_record_data(item, 4))
with ctx.lock:
_service(ctx, current)["ipv4"].add(ipv4)
elif current and item.wType == DNS_TYPE_AAAA and item.wDataLength >= 16:
ipv6 = socket.inet_ntop(socket.AF_INET6, _record_data(item, 16))
with ctx.lock:
_service(ctx, current)["ipv6"].add(ipv6)
rec = item.pNext
except Exception:
return
def resolve_callback(status, context_ptr, instance_ptr):
ctx = _context_from_ptr(context_ptr)
try:
if status == 0 and instance_ptr and ctx is not None:
inst = instance_ptr.contents
full_name = inst.pszInstanceName or ""
instance = _instance_from_service_name(full_name) if full_name else ""
hostname = (inst.pszHostName or "").rstrip(".")
ipv4 = ""
ipv6 = ""
if inst.ip4Address:
raw = inst.ip4Address.contents
ipv4 = socket.inet_ntoa(raw.to_bytes(4, "little"))
if inst.ip6Address:
ipv6 = socket.inet_ntop(socket.AF_INET6, bytes(inst.ip6Address.contents))
if instance:
with ctx.lock:
entry = _service(ctx, instance)
if hostname:
entry["hostname"] = hostname
if ipv4:
entry["ipv4"].add(ipv4)
if ipv6:
entry["ipv6"].add(ipv6)
except Exception:
pass
finally:
if instance_ptr:
dnsapi.DnsServiceFreeInstance(instance_ptr)
if ctx is not None:
with ctx.lock:
ctx.pending_resolves -= 1
if ctx.pending_resolves <= 0:
ctx.resolve_done.set()
def get_dns_sd_data(debug_dns=False):
"""Discover _matter._tcp services using dnsapi.dll."""
ctx = DiscoveryContext()
# py_object plus an explicit keepalive. The browse request only stores the address.
ctx_obj = _ContextBox(ctx)
ctx_ref = ctypes.pointer(ctx_obj)
ctx_ptr = ctypes.cast(ctx_ref, ctypes.c_void_p)
browse_cb = BROWSE_CALLBACK(browse_callback)
resolve_cb = RESOLVE_CALLBACK(resolve_callback)
query = ctypes.create_unicode_buffer("_matter._tcp.local")
req = DNS_SERVICE_BROWSE_REQUEST()
req.Version = DNS_QUERY_REQUEST_VERSION1
req.InterfaceIndex = 0
req.QueryName = ctypes.cast(query, wintypes.LPCWSTR)
req.pBrowseCallback = ctypes.cast(browse_cb, ctypes.c_void_p)
req.pQueryContext = ctx_ptr
cancel = DNS_SERVICE_CANCEL()
status = dnsapi.DnsServiceBrowse(ctypes.byref(req), ctypes.byref(cancel))
if status not in (0, DNS_REQUEST_PENDING):
print(f"DnsServiceBrowse failed: {status}", file=sys.stderr)
return {}
if debug_dns:
print(f"[DEBUG] Browsing _matter._tcp for up to {BROWSE_TIMEOUT}s...", flush=True)
started = time.time()
while time.time() - started < BROWSE_TIMEOUT:
time.sleep(0.25)
with ctx.lock:
count = len(ctx.services)
last_add = ctx.last_add
if count and time.time() - last_add >= BROWSE_QUIET:
break
dnsapi.DnsServiceBrowseCancel(ctypes.byref(cancel))
with ctx.lock:
missing = [name for name, entry in ctx.services.items() if not entry["hostname"]]
if debug_dns:
print(f"[DEBUG] Browse saw {len(ctx.services)} services, resolving {len(missing)}", flush=True)
resolve_names = []
resolve_requests = []
resolve_cancels = []
if missing:
with ctx.lock:
ctx.pending_resolves = len(missing)
ctx.resolve_done.clear()
for instance in missing:
buf = ctypes.create_unicode_buffer(f"{instance}._matter._tcp.local")
rreq = DNS_SERVICE_RESOLVE_REQUEST()
rreq.Version = DNS_QUERY_REQUEST_VERSION1
rreq.InterfaceIndex = 0
rreq.QueryName = ctypes.cast(buf, wintypes.LPWSTR)
rreq.pResolveCompletionCallback = ctypes.cast(resolve_cb, ctypes.c_void_p)
rreq.pQueryContext = ctx_ptr
rcancel = DNS_SERVICE_CANCEL()
rc = dnsapi.DnsServiceResolve(ctypes.byref(rreq), ctypes.byref(rcancel))
if rc not in (0, DNS_REQUEST_PENDING):
with ctx.lock:
ctx.pending_resolves -= 1
if debug_dns:
print(f"[DEBUG] DnsServiceResolve failed for {instance}: {rc}", flush=True)
continue
resolve_names.append(buf)
resolve_requests.append(rreq)
resolve_cancels.append(rcancel)
with ctx.lock:
if ctx.pending_resolves <= 0:
ctx.resolve_done.set()
ctx.resolve_done.wait(RESOLVE_TIMEOUT)
for rcancel in resolve_cancels:
dnsapi.DnsServiceResolveCancel(ctypes.byref(rcancel))
# Keep callback and request objects alive until the cancels above have run.
_keepalive = (browse_cb, resolve_cb, ctx_obj, ctx_ref, query, req, resolve_names, resolve_requests)
data = {}
with ctx.lock:
items = list(ctx.services.items())
for instance, entry in items:
ipv4, ipv6 = _pick_addresses(list(entry["ipv4"]) + list(entry["ipv6"]))
data[instance] = {
"hostname": entry["hostname"],
"ipv4": ipv4,
"ipv6": ipv6,
}
if debug_dns:
print(f"[DEBUG] {instance} {entry['hostname']} {ipv6} {ipv4}", flush=True)
return data
# ---------------- hostname cache ----------------
hostname_cache = {}
def resolve_hostname_cached(hostname, debug_dns=False):
now = time.time()
if hostname in hostname_cache:
ipv4, ipv6, ts = hostname_cache[hostname]
if now - ts < CACHE_TTL:
return ipv4, ipv6
ipv4, ipv6 = "", ""
try:
results = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
for res in results:
family, _, _, _, sockaddr = res
ip = sockaddr[0]
if family == socket.AF_INET and not ipv4:
ipv4 = ip
elif family == socket.AF_INET6 and not ipv6:
ipv6 = _format_ipv6(ip)
except Exception as e:
if debug_dns:
print(f"[DEBUG] getaddrinfo failed for {hostname}: {e}")
hostname_cache[hostname] = (ipv4, ipv6, now)
return ipv4, ipv6
# ---------------- help ----------------
def print_help():
print("""Usage: matter-map [LOCATION] [OPTIONS]
Positional arguments:
LOCATION Filter devices by location name
Options:
--help Show this help message and exit
--sort=FIELD Sort by field: label, location, instance, hostname, ipv4, ipv6
--reverse Reverse sort order
--debug-dns Print debug info for DNS-SD queries""")
# ---------------- main ----------------
def main():
sort_key = "label"
reverse = False
location_arg = None
debug_dns = False
args = sys.argv[1:]
positional_args = []
for arg in args:
if arg == "--help":
print_help()
sys.exit(0)
elif arg == "--reverse":
reverse = True
elif arg == "--debug-dns":
debug_dns = True
elif arg.startswith("--sort="):
sort_key = arg.split("=", 1)[1]
elif arg.startswith("-"):
print(f"Unknown option: {arg}", file=sys.stderr)
sys.exit(1)
else:
positional_args.append(arg)
if len(positional_args) > 1:
print("Error: only one location name may be specified", file=sys.stderr)
sys.exit(1)
if positional_args:
location_arg = positional_args[0]
valid_sorts = {"label", "location", "instance", "hostname", "ipv4", "ipv6"}
if sort_key not in valid_sorts:
print(f"Invalid sort key: {sort_key}", file=sys.stderr)
print(f"Valid options: {', '.join(sorted(valid_sorts))}", file=sys.stderr)
sys.exit(1)
id_to_name, name_to_id = get_locations()
location_id = None
if location_arg:
location_id = name_to_id.get(location_arg)
if not location_id:
print("Unknown location", file=sys.stderr)
sys.exit(1)
devices = get_matter_devices(location_id)
dns_data = get_dns_sd_data(debug_dns)
for d in devices:
dns = dns_data.get(d["instance"], {})
d["hostname"] = dns.get("hostname", "UNKNOWN") or "UNKNOWN"
d["ipv4"] = dns.get("ipv4", "")
d["ipv6"] = dns.get("ipv6", "")
d["location"] = id_to_name.get(d.get("locationId"), "UNKNOWN")
to_resolve = [
d for d in devices
if d["hostname"] not in ("", "UNKNOWN") and not (d["ipv4"] or d["ipv6"])
]
with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
future_to_device = {
executor.submit(resolve_hostname_cached, d["hostname"], debug_dns): d
for d in to_resolve
}
for future in as_completed(future_to_device):
d = future_to_device[future]
try:
ipv4, ipv6 = future.result()
d["ipv4"] = ipv4 or d["ipv4"]
d["ipv6"] = ipv6 or d["ipv6"]
except Exception:
pass
devices.sort(key=lambda r: r.get(sort_key, ""), reverse=reverse)
grouped = defaultdict(list)
for r in devices:
grouped[r.get("location", "UNKNOWN")].append(r)
print(
f"{'DEVICE LABEL':<25} {'LOCATION':<15} {'INSTANCE NAME/NETWORK ID':<40} "
f"{'HOSTNAME':<30} {'IPv6 ADDRESS':<40} {'IPv4 ADDRESS':<20}"
)
print("-" * 180)
for location in sorted(grouped):
for r in grouped[location]:
print(
f"{r['label']:<25} "
f"{location:<15} "
f"{r['instance']:<40} "
f"{r['hostname']:<30} "
f"{r['ipv6']:<40} "
f"{r['ipv4']:<20}"
)
if __name__ == "__main__":
main()